简体   繁体   English

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

[英]Laravel 7 - Redirecting different user roles to different view

  • The LoginController had this code before: LoginController 之前有这段代码:

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

  • Then I changed it for:然后我将其更改为:

    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');
        }
    }
  • In the model User I have this for the roles:在 model 用户中,我有这个角色:
     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;
        }

With the new changes on the LoginController I have no problem with the login, but obviously only redirect to the main view.通过 LoginController 上的新更改,我对登录没有任何问题,但显然只重定向到主视图。 So, I want to add the redirect view depend on the role, but when I add the public function login() that it had before it returns an error with the function userRole() on the model User.因此,我想添加取决于角色的重定向视图,但是当我添加public function login()时,它在 Z20F35E630DAF44DFAC4C36 用户上返回错误与function userRole()之前。 The error is错误是

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

You don't need to override the login method.您不需要覆盖login方法。 The login method currently will make a call to the authenticated method to see if it returns true truthy value and then return that as the response. login方法当前将调用经过authenticated的方法以查看它是否返回 true 真实值,然后将其作为响应返回。 You can override the authenticated method and have it return your redirect based on your conditions.您可以覆盖经过authenticated的方法并让它根据您的条件返回您的重定向。

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

The error is caused by trying to access an attribute/relationship which doesn't exist, which returns null :该错误是由尝试访问不存在的属性/关系引起的,该属性/关系返回null

$this->role

The User belongs to many Role so there are multiple roles not a single one.用户属于许多角色,因此有多个角色而不是一个角色。

You could have a method to check for a single role:您可以有一种方法来检查单个角色:

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

Then you could adjust your conditionals:然后你可以调整你的条件:

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

Or use the hasRoles method instead:或者改用hasRoles方法:

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

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

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