In this example, How to pass a few parameters to middleware with an OR clause in Laravel 5.2
Instead of adding a few arguments to your descriptor method and having to update it every time you add a new role to the application, you can make it dynamic.
Middleware
/** * 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
Route::group(['middleware' => ['role_check:default,admin,manager']], function() { Route::get('/user/{user_id}', array('uses' => ' UserController@showUserDashboard ', 'as' => 'showUserDashboard')); });
This will check if the authenticated user has at least one of the roles provided, and if so, passes the request to the next middleware stack. Of course, the hasRole() method and the roles themselves must be implemented by you.
You can use 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); } } }
source share