Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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);
}
like image 494
Tropicalista Avatar asked Jun 23 '15 20:06

Tropicalista


2 Answers

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.

like image 74
Stuart Wagner Avatar answered Oct 13 '22 00:10

Stuart Wagner


Another approach is to override authenticated method

public function authenticated()
    {
        if(Auth::check()) {
            if(\Auth::user()->hasRole('Super Admin')) {
                return redirect('/admin-dashboard');
            } else {
                return redirect('/user-dashbaord');
            }
        }    
    }
like image 45
sumit Avatar answered Oct 12 '22 23:10

sumit