In default Laravel, there's one constant responsible for the redirection of logged-in users:
app/Providers/RouteServiceProvider.php:
1class RouteServiceProvider extends ServiceProvider2{3 /**4 * The path to the "home" route for your application.5 * Typically, users are redirected here after authentication.6 */7 public const HOME = '/home';
Laravel itself uses that RouteServiceProvider::HOME
in the Middleware which is fired if the user is already logged in.
app/Http/Middleware/RedirectIfAuthenticated.php:
1class RedirectIfAuthenticated 2{ 3 public function handle(Request $request, Closure $next, ...$guards) 4 { 5 $guards = empty($guards) ? [null] : $guards; 6 7 foreach ($guards as $guard) { 8 if (Auth::guard($guard)->check()) { 9 return redirect(RouteServiceProvider::HOME);10 }11 }12 13 return $next($request);14 }15}
So, first, you need to change that redirect()
to your custom logic.
Let's say that your logic will be inside of your User
model, like this:
app/Models/User.php:
1class User extends Authenticatable 2{ 3 // ... 4 5 public function getRedirectRoute() 6 { 7 return match((int)$this->role_id) { 8 1 => 'student.dashboard', 9 2 => 'teacher.dashboard',10 // ...11 };12 }13}
Then, in the RedirectIfAuthenticated
Middleware, you change it to this:
1if (Auth::guard($guard)->check()) {2 return redirect(Auth::user()->getRedirectRoute());3}
Laravel Breeze
Laravel Breeze uses the same RouteServiceProvider::HOME
in two places separately: Controller for the Registration and for the Login.
app/Http/Controllers/Auth/RegisteredUserController.php:
1public function store(Request $request): RedirectResponse2{3 // ...4 5 Auth::login($user);6 7 return redirect(RouteServiceProvider::HOME);8}
Change the last line to:
1return redirect(auth()->user()->getRedirectRoute());
And then the Login Controller.
app/Http/Controllers/Auth/AuthenticatedSessionController.php:
1public function store(LoginRequest $request): RedirectResponse2{3 $request->authenticate();4 5 $request->session()->regenerate();6 7 return redirect()->intended(RouteServiceProvider::HOME);8}
Change the last line to:
1return redirect()->intended(auth()->user()->getRedirectRoute());
No comments or questions yet...