Laravel - how to redirect user to different pages based on different user role?


Posted 5 years ago by Ryan Dhungel

Category: Laravel

Viewed 65047 times

Estimated read time: 2 minutes

Want to know how to redirect user after login in your Laravel app? Then this short article will help you out! By default laravel will redirect a user to the home page like so: protected $redirectTo = '/home';

To change that default behaviour, add the following code in App/Http/Controllers/Auth/LoginController.php. This will redirect users (after login) to where ever you want.

// inside LoginController class
use AuthenticatesUsers;

// check if authenticated, then redirect to dashboard
protected function authenticated() {
	if (Auth::check()) {
		return redirect()->route('dashboard');
	}
}

We are simply using AuthenticatesUsers trait inside LoginController so that we can use one of its method called authenticated(). If you are curious about this trait, you can search for AuthenticatesUsers in your editor and have a look at it. In sublime, you can use command+p or control+p

By default this method is left empty in AuthenticatesUsers trait. You can apply whatever logic you want to apply inside this method to redirect users. 

Redirect user based on Role in Laravel

If your users are based on roles, then you can redirect them (after login) to a particular page based on their role such as Admin, Author and Subscriber. Have a look at the code sample below:

protected function authenticated(Request $request, $user) {
	 if ($user->role_id == 1) {
	 	return redirect('/admin');
	 } else if ($user->role_id == 2) {
	 	return redirect('/author');
	 } else {
	 	return redirect('/blog');
	 }
}