If you use Laravel Jetstream, you may want to customize where login form redirects to, after submission. For example, what if you want to redirect to different dashboards or URLs, depending on user's role?
Under the hood, Laravel Jetstream uses features from Laravel Fortify.
So, first, you need to have your custom logic.
Let's say that your logic will be inside of your User
model like this:
app/Models/User.php:
class User extends Authenticatable{ // ... public function getRedirectRoute(): string { return match((int)$this->role_id) { 1 => 'student.dashboard', 2 => 'teacher.dashboard', // ... }; }}
Next, we must bind the LoginResponse
from Fortify to customize the redirect. Typically, this should be done using the register()
method in the FortifyServiceProvider
class.
app/Providers/FortifyServiceProvider.php:
use Illuminate\Http\RedirectResponse;use Laravel\Fortify\Contracts\LoginResponse; class FortifyServiceProvider extends ServiceProvider{ public function register(): void { $this->app->instance(LoginResponse::class, new class implements LoginResponse { public function toResponse($request): RedirectResponse { return redirect(auth()->user()->getRedirectRoute()); } }); } // ...}
If you use Breeze and want to redirect the user after login, you can check this tutorial: How to Change Redirect After Login/Register in Laravel Breeze.
Hi, just a quick question: The getRedirectRoute()-function seems to return a named route?
The redirect in FortifyServiceProvider however redirects to an url. So this would not work and you would have to change it to return redirect()->route(auth()->user()->getRedirectRoute())? (https://laravel.com/docs/11.x/redirects#redirecting-named-routes)