简体   繁体   English

如何根据 Laravel 8 中的用户角色或权限重定向到不同的视图?

[英]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 .我将下面的函数放在LoginController类中以将用户重定向到不同的视图,登录后我得到了这个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;首先把它放在你的LoginController类中: use Illuminate\\Support\\Facades\\Auth;

  2. comment out this line protected $redirectTo =... and also add this function in the LoginController class:注释掉这行protected $redirectTo =...并在LoginController类中添加这个函数:

    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.查看app\\Http\\Middleware\\RedirectIfAuthenticated.phphandle方法,您将看到在用户通过 Auth 检查后,他们会收到重定向。

This class was designed to redirect users to the correct landing page once authenticated.此类旨在通过身份验证后将用户重定向到正确的landing页面。

    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);
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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