How to pass multiple parameters to middleware with OR condition in Laravel 5.2

后端 未结 6 1540
误落风尘
误落风尘 2020-12-06 00:48

I am trying to set permission to access an action to two different user roles Admin, Normal_User as shown below.

Route::group([\'middleware\' => [\'role_c         


        
6条回答
  •  日久生厌
    2020-12-06 01:07

    Instead of adding multiple arguments to your handle method and having to update it every time you add a new role to your 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 will need to be implemented by you.

提交回复
热议问题