如何在Laravel 5.6中创建具有多个角色的中间件



我正在使用Sentinel包,例如,我创建了中间件PCMiddleware

public function handle($request, Closure $next)
{
$roles = array_slice(func_get_args(), 2); 
foreach ($roles as $role) {
if(Sentinel::check() && Sentinel::getUser()->inRole($role)){
return $next($request);
} else {
return redirect()->route('admin.errors');
}
}    
}

路线

$route->get('dashboard', ['as' => 'dashboard', 'uses' => 'AdminController@dashboard'])->middleware('role_check:member,hrd,super-admin');

我也创建了角色为hrd的用户,即任何具有hrd角色的用户都可以访问仪表板,但当我以404登录时,即使我只有hrd角色,我如何能够访问/dashboard

也许像这样,如果用户有这三个角色中的任何一个,那么他可以访问路线,

在Laravel中已经有一种为中间件传输参数的方法。你可以在这里阅读

public function handle($request, Closure $next)
{
$roles = array_slice(func_get_args(), 2); 
$status = false;
foreach ($roles as $role) {
if(Sentinel::check() && Sentinel::getUser()->inRole($role)){
$status = true;
break;
}
}    
if ($status) {
return $next($request);
} 
return redirect()->route('admin.errors');
}

在本例中,如果至少有一个传递的参数存在,那么您的代码就会工作

最新更新