laravel 5 redirect user after login based on user&

2019-04-10 02:33发布

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?

4条回答
女痞
2楼-- · 2019-04-10 03:11

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

}
查看更多
smile是对你的礼貌
3楼-- · 2019-04-10 03:18

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.

查看更多
可以哭但决不认输i
4楼-- · 2019-04-10 03:33

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') ;
    }
}
查看更多
我欲成王,谁敢阻挡
5楼-- · 2019-04-10 03:34

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);
}
查看更多
登录 后发表回答