Laravel – How to redirect intended user to a different route based on their role

laravellaravel-5

I'd like to redirect my user to different route, based on their role. I have two secured area in my app, "admin" and "dashboard". I'd like to check if user is authenticated, then redirect to intended, but if user has role editor it should be redirected to dashboard, otherwise if he has role admin should be redirected to admin area.

I'm using AuthenticatesAndRegistersUsers class in my login. I have this on my custom controller:

 /**
 * The default redirecTo path.
 *
 */
 protected $redirectTo = '/dashboard';

So when a user is authenticated it will be redirected to dashboard, but I'd like to check if the intended url is on admin group route and if user has admin role it should be redirected to admin area.

I'm using this middleware to redirect to login:

public function handle($request, Closure $next)
{
    if ($this->auth->guest())
    {
        if ($request->ajax())
        {
            return response('Unauthorized.', 401);
        }
        else
        {
            return redirect()->guest('auth/login');
        }
    }

    return $next($request);
}

Best Answer

You could overwrite the redirectPath method used by the trait in your AuthController to inject the logic you need. Something like this:

/**
 * Get the post register / login redirect path.
 *
 * @return string
 */
public function redirectPath()
{
    // Logic that determines where to send the user
    if (\Auth::user()->type == 'admin') {
        return '/admin';
    }

    return '/dashboard';
}

EDIT:

Laravel uses the following declaration in the AuthenticatesAndRegistersUsers trait to redirect the user after successful login:

return redirect()->intended($this->redirectPath());

This will try to redirect the user to the previously attempted URL.

If you need to redirect users to the right place when they're already logged in, that would be best done by adding more logic to your authentication middleware.

Related Topic