如何在路由组中注册多个中间件权限?-Laravel [英] How can i register multiple middleware permissions in routegroup?-Laravel

查看:88
本文介绍了如何在路由组中注册多个中间件权限?-Laravel的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有3个角色,分别是管理员,导师和学生.我想将它们放在3个不同的组中,但是我希望管理员在所有组中.我尝试了不同的方法将管理员添加到其他路由,但是它不起作用.如何让管理员使用导师中间件中的所有路由?这是我的代码

I have 3 roles roles, admin, tutor and student. i want to place them in 3 different goups, i however want the admin to be in all the groups. I have tried different methods to add the admin to other routes but it's not working. How can i make admin use all routes in tutor's middleware? Here is my code

AdminMiddleware ,与所有其他软件类似

AdminMiddleware, similar to all the others

class AdminMiddleware
{
    public function handle($request, Closure $next)
    {
        if(Auth::check() && Auth::user()->isRole()=="admin") {
            return $next($request);
        }
        return redirect('login');
    }
}

routesmiddleware-在web.php中

Route::group(['middleware'=>['auth'=>'admin']], function (){
   //admin routes
}
Route::group(['middleware'=>['auth'=>'tutor']], function (){
//tutor routes

}

在Kernel.php中

'admin' => \App\Http\Middleware\AdminMiddleware::class,
'tutor' => \App\Http\Middleware\TutorMiddleware::class,
'student' => \App\Http\Middleware\StudentMiddleware::class,

在用户模型中

public function isRole(){
    return $this->role; 
}

推荐答案

您可以做的是定义一个以支持的角色作为参数的中间件:

What you can do is define a middleware that takes the supported roles as argument:

class HasRoleMiddleware
{
    public function handle($request, Closure $next, ...$roles)
    {
        if(Auth::check() && in_array(Auth::user()->getRole(), $roles)) {
            return $next($request);
        }

        return redirect('login');
    }
}

此中间件期望User::getRole()返回角色为字符串,即admintutor.然后,您需要像已经完成的那样在Kernel.php中定义中间件:

This middleware expects that User::getRole() returns the role as string, i.e. admin or tutor. Then you need to define the middleware in Kernel.php as you have already done:

'any_role' => \App\Http\Middleware\HasRoleMiddleware::class,

最后,您可以像这样使用中间件:

And finally you can use the middleware like this:

Route::group(['middleware' => 'auth'], function () {
    Route::group(['middleware' => 'any_role:admin'], function () {
        // admin routes
    }

    Route::group(['middleware' => 'any_role:admin,tutor'], function () {
       // tutor routes
    }
}

如您所见,我还将执行角色检查的路由组嵌套在另一个检查身份验证的路由组中.这样可以提高可读性,并减少在以后的路由扩展中忘记进行身份验证检查的风险.

As you can see, I've also nested the route groups which perform role checks inside another route group which checks for authentication. This makes it more readable and reduces the risk you forget an authentication check in a future extension of your routes.

这篇关于如何在路由组中注册多个中间件权限?-Laravel的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆