这是一个例子
如何在Laravel 5.2中使用OR条件将多个参数传递给中间件
而不是将多个参数添加到您的处理方法中,并且每次向应用程序添加新角色时都必须更新它,您可以使其动态。
中间件
public function handle($request, Closure $next) {
$roles = array_slice(func_get_args(), 2);
foreach ($roles as $role) {
try {
Role::whereName($role)->firstOrFail();
if (Auth::user()->hasRole($role)) {
return $next($request);
}
} catch (ModelNotFoundException $exception) {
dd('Could not find role ' . $role);
}
}
Flash::warning('Access Denied', 'You are not authorized to view that content.');
return redirect('/');
}
路由
Route::group(['middleware' => ['role_check:default,admin,manager']], function() {
Route::get('/user/{user_id}', array('uses' => 'UserController@showUserDashboard', 'as' => 'showUserDashboard'));
});
这将检查经过身份验证的用户是否具有至少一个提供的角色,如果是,则将请求传递给下一个中间件堆栈。当然,
hasRole()
方法和角色本身需要由您实现。
您可以使用php 5.6
public function handle($request, Closure $next, ...$roles)
{
foreach ($roles as $role) {
try {
if ($request->user()->can($role)) {
return $next($request);
}
} catch (ModelNotFoundException $exception) {
abort(403);
}
}
}