简体   繁体   中英

How can I redirect to different views based on user role or privilege in Laravel 8?

I put the function below in the LoginController class to redirect users to different views, and when after login I got this 419|expired page .

protected function authenticated(Request $request, $user) {
    if ($user->PRIVILEGE == 'C') {
        return redirect()->route('/users');
    } else if ($user->PRIVILEGE == 'B') {
        return redirect('/blog');
    } else {
        return redirect('/');
    }
}
  1. First put this in your LoginController class: use Illuminate\\Support\\Facades\\Auth;

  2. comment out this line protected $redirectTo =... and also add this function in the LoginController class:

    public function redirectPath() {

     if(Auth::user()->privilege =='C'){ return '/users'; } if(Auth::user()->privilege=='B'){ return '/blog'; }

    }

Have a look inside the handle method in app\\Http\\Middleware\\RedirectIfAuthenticated.php you will see that after a user has passed the Auth check they are greeted with a redirect.

This class was designed to redirect users to the correct landing page once authenticated.

    public function handle($request, Closure $next, $guard = null)
    {
        if (Auth::guard($guard)->check()) {
            $user = Auth::user();
            if ($user->PRIVILEGE == 'C') {
                return redirect()->route('/users');
            }
            if ($user->PRIVILEGE == 'B') {
                return redirect('/blog');
            } 
            return redirect('/');
        }

        return $next($request);
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM