Laravel 7 - 将不同的用户角色重定向到不同的视图

Laravel 7 - Redirecting different user roles to different view


    class LoginController extends Controller
    {
        public function showLoginForm(){
            $roles = Role::all();
            return view('auth.login', compact('roles'));
        }
    
        public function logout(Request $request){
            Auth::logout();
            $request->session()->flush();
            return redirect('/');
        }
    
        public function login()
        {
            $credentials = $this->validate(request(),[
                'email' => 'email|required|string',
                'password' => 'required|string',
            ]);
    
           
            if (Auth::attempt ($credentials)){//auth attemptdevuelve verdadero o falso en caso de que las credenciales correspondan o no
            //Inician cambios RDAN
            $user = Auth::user();
            if($user->userRole() == 'admin') {
                return redirect('main');
            } else if($user->userRole() == 'externo') {
                return redirect('es/user_form');
            } else if($user->userRole() == 'profesor') {
                return redirect('profesor_site');
            } else if($user->userRole() == 'registrador') {
                return redirect('select_lang');
            } else {
                return back()->withErrors(['email' => 'Incorrect user permissions']) 
                ->withInput(request(['email']));
            }
            //Terminan cambios RDAN
                    
            }else{
            return back()->withErrors(['email' => 'Incorrect user permissions']) 
            ->withInput(request(['email'])); }
        }
    }


    class LoginController extends Controller
    {
      use AuthenticatesUsers;
    
        /**
         * Where to redirect users after login.
         *
         * @var string
         */
        protected $redirectTo = '/main';//RouteServiceProvider::HOME;
    
        /**
         * Create a new controller instance.
         *
         * @return void
         */
        public function __construct()
        {
            $this->middleware('guest')->except('logout');
        }
    }
     public function roles()
        {
            return $this->belongsToMany(Role::class,'assigned_roles');
        }
    
        public function isAdmin(){
            return $this->hasRoles(['admin']);
        }
    
        public function hasRoles(array $roles)
        {
            return $this->roles->contains(fn($role, $key) => in_array($role->name, $roles));
        }
    
        public function userRole(){
            return $this->role->nombre_rol;
        }

随着 LoginController 的新变化,我的登录没有问题,但显然只能重定向到主视图。所以,我想根据角色添加重定向视图,但是当我添加它之前的 public function login() returns 时,模型用户上的 function userRole() 出现错误。错误是

ErrorException Trying to get property 'nombre_rol' of non-object http://localhost/Servescol2.0.2/public/login

您不需要覆盖 login 方法。 login 方法当前将调用 authenticated 方法以查看它是否 return 真实值,然后 return 将其作为响应。您可以重写 authenticated 方法并使其 return 根据您的条件进行重定向。

protected function authenticated(Request $request, $user)
{
    if ($user->hasRoles(['admin'])) {
        return redirect('main');
    }
    ...
}

错误是由于尝试访问不存在的 attribute/relationship 而导致的,returns null:

$this->role

用户属于多个角色,因此存在多个角色,而不是一个。

您可以使用一种方法来检查单个角色:

public function hasRole($role)
{
    return $this->roles->contains('name', $role);
}

然后你可以调整你的条件:

if ($user->hasRole('admin')) {

或改用hasRoles方法:

if ($user->hasRoles(['admin']) {