laravel 5 redirect user after login based on user&

2019-04-10 02:44发布

问题:

My 'users' table has a 'role' column and when users are registered or logged in, I want them to be redirected based on their role column. how can I do that?

回答1:

I added this function to AuthController.php and everything fixed magically

public function authenticated($request , $user){
    if($user->role=='super_admin'){
        return redirect()->route('admin.dashboard') ;
    }elseif($user->role=='brand_manager'){
        return redirect()->route('brands.dashboard') ;
    }
}


回答2:

If you are using the Authentication system provided with Laravel you can override the redirectPath method in your Auth\AuthController.

For example, this would redirect a user with role 'admin' to /admin and any other user to /account:

public function redirectPath()
{
    if (\Auth::user()->role == 'admin') {
        return "/admin";
        // or return route('routename');
    }

    return "/account";
    // or return route('routename');
}

You could also use Laravel Authorization (introduced in 5.1.11) to manage role logic.



回答3:

In laravel 5.7 there is no AuthController.php so you have to go Controllers\Auth\LoginController.php and add the below function,

If the redirect path needs custom generation logic you may define a redirectTo method instead of a redirectTo property

protected function redirectTo()
{

    if($user->role=='super_admin'){
        return '/path1';
    }elseif($user->role=='brand_manager'){
        return '/path2';
    }   

}


回答4:

You can do this handle the request in the Middleware RedirectIfAuthenticated.php inside the handle function like this:

/**
 * Handle an incoming request.
 *
 * @param  \Illuminate\Http\Request  $request
 * @param  \Closure  $next
 * @param  string|null  $guard
 * @return mixed
 */
public function handle($request, Closure $next, $guard = null)
{
    if (Auth::guard($guard)->check()) {
        if (Auth::user()->role == 'admin') {
            return redirect('/admin');
        }else{
            return redirect('/');
        }
    }

    return $next($request);
}