此示例 如何在 Laravel 5.2 中使用 OR 条件将多个参数传递给中间件
无需向 handle 方法添加多个参数,并且每次向应用程序添加新角色时都必须对其进行更新,而是可以使其动态化。
中间件
/**
* Handle an incoming request.
*
* @param $request
* @param Closure $next
* @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
*/
public function handle($request, Closure $next) {
$roles = array_slice(func_get_args(), 2); // [default, admin, manager]
foreach ($roles as $role) {
try {
Role::whereName($role)->firstOrFail(); // make sure we got a "real" role
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.'); // custom flash class
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);
}
}
}