在中间件中获取Laravel当前路由组 [英] Get laravel current route group in middleware
问题描述
在Laravel中间件中是否可以获取当前路由的父路由组?
Is there a way to get the parent route group of current route in Laravel middlewares?
public function handle($request, Closure $next, $guard = null)
{
// here I mean
}
推荐答案
您无法从路线中获得该组,尤其是您可以将组嵌套在其他组中.
You can't get the group from a route, especially that you can nest groups within other groups.
分辨当前请求属于哪个组的最简单方法是在中间件中添加一个参数-有关更多详细信息,请参见文档:
The easiest way to be able to tell which group current request belongs to would be to add a parameter to your middleware - see the docs for more details here: https://laravel.com/docs/5.2/middleware#middleware-parameters
首先,在您的 handle()方法中声明参数:
First, declare the parameter in your handle() method:
public function handle($request, Closure $next, $group = null)
{
// your logic here
}
然后,在将中间件分配给组时,可以将组名作为参数传递:
Then, when assigning middleware to groups, you can pass group name as a parameter:
Route::group(['middleware' => 'yourmiddleware:groupname'], function () {
// your routes go here
});
然后,在中间件中,您可以根据传递的组名称执行不同的操作:
Then in your middleware you can do different actions based on the group name passed:
if ($group === 'groupname') {
// some custom logic here
}
如果您打算对不同的组执行的逻辑不同,则应考虑实现多个中间件,而不是将组名作为参数传递,以保持职责分离.
If the logic you plan to do for different groups is different you should consider implementing multiple middlewares instead of passing group name as a parameter just to keep responsibilities separated.
这篇关于在中间件中获取Laravel当前路由组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!