【问题标题】:How to assign two middleware to the same group of routes. Laravel如何将两个中间件分配给同一组路由。拉拉维尔
【发布时间】:2020-03-03 07:44:00
【问题描述】:

我有 3 个中间件,分配了所有不同的路由。这些是对应于每个用户类型的路由。

像这样:

在我的路线中我有这个

Route::group(['middleware' => 'auth'], function () {
    Route::resource('/', 'DashController');
    Route::get('/logout')->name('logout')->uses('Auth\LoginController@logout');

    Route::group(['middleware' => ['director']], function () {
        //survey
        //questions
        //groups
        //forum
    });

    Route::group(['middleware' => ['super']], function () {
        //import
    });

    Route::group(['middleware' => ['admin']], function () {
        //semester
        //users
        //sections
        //category
        //classrooms
        //careers
        //courses
    });

});

我需要做的是将director 组内的路由也添加到admin 组。管理员中间件检查用户是管理员还是超级管理员,这就是为什么超级组只有导入路由。

我试过像这样将一个组嵌套在另一个组中:

Route::group(['middleware' => ['director', 'admin']], function () {
        //survey
        //questions
        //groups
        //forum
    Route::group(['middleware' => ['admin']], function () {
        //semester
        //users
        //sections
        //category
        //classrooms
        //careers
        //courses
    });
});

我也尝试过与上面相同的方法,但第一组是这样的

Route::group(['middleware' => ['director'], ['admin']], function () {});

从让双方共享这些路线的意义上说,没有任何效果。我该怎么做?

【问题讨论】:

    标签: laravel


    【解决方案1】:

    这是使用该级联设置的一种方法:

    必须反过来考虑这一点,需要最高角色到最低角色,因为您在这里有一个权限漏斗,顶部可以访问所有内容,接下来几乎所有内容,然后底部最少。

    Route::group(['roles' => 'super', 'middleware' => 'check', ...], function () {
        // only routes for 'super admin'
    
        Route::group(['roles' => 'admin', ...], function () {
            // routes only for superadmin and admin
    
            Route::group(['roles' => 'director', ...], function () {
                // remaining routes that director, admin and super admin can access
    
                Route::get('sometest', function () { })->name('for-all');
            });
        })
    });
    

    我们将使用带有路由参数/属性的路由组的级联能力。

    名为for-all 的路由最终会得到一个名为roles 的操作参数,该参数将是一个数组['super', 'admin', 'director']。我们可以让中间件使用它,这样我们就知道要检查什么。

    class CheckMiddleware
    {
        public function handle($request, Closure $next)
        {
            $roles = $request->route()->getAction('roles', []);
    
            foreach ((array) $roles as $role) {
                // if the user has this role, let them pass through
                if (...) {
                    return $next($request);
                }
            }
    
            // user is not one of the matching 'roles'
            return redirect('/');
        }
    }
    

    我不知道您如何检查用户以了解他们的“角色”,但这将在此中间件中发挥作用。

    【讨论】:

      猜你喜欢
      • 2016-02-06
      • 2019-06-15
      • 2019-01-01
      • 2017-03-16
      • 2018-09-15
      • 2020-06-05
      • 1970-01-01
      • 2019-09-09
      • 1970-01-01
      相关资源
      最近更新 更多