Get laravel current route group in middleware

╄→гoц情女王★ 提交于 2019-12-10 18:13:43

问题


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
}

回答1:


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

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.



来源:https://stackoverflow.com/questions/38869982/get-laravel-current-route-group-in-middleware

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!