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


Posted 2 months ago | by Ryan Dhungel | on Laravel  | Viewed 273 times

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


Specials


Build Laravel React CRUD/SPA APP in 2 hours
Build Laravel React CRUD/SPA APP in 2 hours

Build Laravel React CRUD/SPA APP in 2 hours

COUPON CODE: REACTCRUD with 90% off


Laravel with React JS - Build Twitter Like Real Ti...
Laravel with React JS - Build Twitter Like Real Time Web App

Laravel with React JS - Build Twitter Like Real Time Web App

COUPON CODE: LARAVELREACT with 90% off


Learn Laravel Building Multi User Blogging Platfor...
Learn Laravel Building Multi User Blogging Platform with SEO


React Redux Firebase CRUD App with Authentication
React Redux Firebase CRUD App with Authentication

React Redux Firebase CRUD App with Authentication

COUPON CODE: RRFTEN with 86% off


Become a Master of JavaScript from Scratch in 2018
Become a Master of JavaScript from Scratch in 2018

Become a Master of JavaScript from Scratch in 2018

COUPON CODE: JSMASTERSALE with 92% off


REACT - Up and Running with React ES6 and Open Sou...
REACT - Up and Running with React ES6 and Open Source API


Sublime Text for Rapid Web Development
Sublime Text for Rapid Web Development

Sublime Text for Rapid Web Development

COUPON CODE: LEARNSUBLIME with 90% off