Tinkerwell - The PHP Scratchpad

How to override login redirects in Jetstream or Fortify

Published on by

How to override login redirects in Jetstream or Fortify image

Recently, I was working on a project using Laravel Jetstream and ran into a scenario where I needed to redirect users to different routes depending on the type of user they were upon login. Imagine you have regular users and admins, and admins have a special dashboard that only they can see. I usually prefer to redirect admins to their special dashboard when they login.

Using Laravel Jetstream or Fortify, it's not immediately apparent how to do this, especially when using two factor authentication.

How authentication works in Jetstream and Fortify

Jetstream uses Laravel Fortify under the hood, so the process is exactly the same for applications running Fortify by itself and projects running Jetstream.

Fortify uses action pipelines to route each request through a series of classes that take care of a single task such as attempting to authenticate the user or redirecting them if they have two factor authentication set up.

How to override the redirection step

Fortify allows you to completely customize these pipelines if you need to, but there's an easier way to override the redirection step.

The last step in the authentication pipeline grabs the Laravel\Fortify\Contracts\LoginResponse class out of the service container and returns it. That means we can override the LoginResponse class with a custom LoginResponse class of our own, and perform the custom redirects there.

The default LoginResponse class looks like this:

<?php
 
namespace Laravel\Fortify\Http\Responses;
 
use Laravel\Fortify\Contracts\LoginResponse as LoginResponseContract;
 
class LoginResponse implements LoginResponseContract
{
/**
* Create an HTTP response that represents the object.
*
* @param \Illuminate\Http\Request $request
* @return \Symfony\Component\HttpFoundation\Response
*/
public function toResponse($request)
{
return $request->wantsJson()
? response()->json(['two_factor' => false])
: redirect()->intended(config('fortify.home'));
}
}

Since Fortify uses actions that perform a single task, the LoginResponse step is really clean and simple.

To customize the redirects, first let's add our custom LoginResponse class in the app/Http/Responses directory. Then, we can customize the toResponse method to redirect the user to different routes depending on the type of user they are.

<?php
 
namespace App\Http\Responses;
 
use Laravel\Fortify\Contracts\LoginResponse as LoginResponseContract;
 
class LoginResponse implements LoginResponseContract
{
/**
* @param $request
* @return mixed
*/
public function toResponse($request)
{
$home = auth()->user()->is_admin ? '/admin' : '/dashboard';
 
return redirect()->intended($home);
}
}

Then, in the FortifyServiceProvider, we need to bind our custom LoginResponse class in order to override the default that's provided with Fortify.

<?php
 
namespace App\Providers;
 
// ...
use App\Http\Responses\LoginResponse;
use Laravel\Fortify\Contracts\LoginResponse as LoginResponseContract;
 
class FortifyServiceProvider extends ServiceProvider
{
/**
* Bootstrap any application services.
*
* @return void
*/
public function boot()
{
// ...
 
$this->app->singleton(LoginResponseContract::class, LoginResponse::class);
}
}

Two Factor Authentication

This worked almost perfectly for my needs. There is one missing piece though - two factor authentication. If a user has two factor authentication enabled and logs in, Fortify returns a different response class. Thankfully, the two factor authentication class is also bound to the service container. This time, we'll need to override the Laravel\Fortify\Http\Responses\TwoFactorLoginResponse class in the container. Adding a couple more lines to the FortifyServiceProvider should do the trick.

<?php
 
namespace App\Providers;
 
// ...
use App\Http\Responses\LoginResponse;
use Laravel\Fortify\Contracts\LoginResponse as LoginResponseContract;
use Laravel\Fortify\Contracts\TwoFactorLoginResponse as TwoFactorLoginResponseContract;
 
class FortifyServiceProvider extends ServiceProvider
{
/**
* Bootstrap any application services.
*
* @return void
*/
public function boot()
{
// ...
 
$this->app->singleton(LoginResponseContract::class, LoginResponse::class);
$this->app->singleton(TwoFactorLoginResponseContract::class, LoginResponse::class);
}
}

Note: I'm overriding the TwoFactorLoginResponse class with the same custom LoginResponse class since the functionality should be exactly the same.

Overriding other Jetstream and Fortify functionality

Other features in Jetstream and Fortify can be customized in a very similar way. If you source dive into the FortifyServiceProvider included in the package (not the one specific to your project) and scroll down to the registerResponseBindings method, you should see something similar to this:

<?php
 
namespace Laravel\Fortify;
 
// ...
 
class FortifyServiceProvider extends ServiceProvider
{
// ...
 
/**
* Register the response bindings.
*
* @return void
*/
protected function registerResponseBindings()
{
$this->app->singleton(FailedPasswordConfirmationResponseContract::class, FailedPasswordConfirmationResponse::class);
$this->app->singleton(FailedPasswordResetLinkRequestResponseContract::class, FailedPasswordResetLinkRequestResponse::class);
$this->app->singleton(FailedPasswordResetResponseContract::class, FailedPasswordResetResponse::class);
$this->app->singleton(FailedTwoFactorLoginResponseContract::class, FailedTwoFactorLoginResponse::class);
$this->app->singleton(LockoutResponseContract::class, LockoutResponse::class);
$this->app->singleton(LoginResponseContract::class, LoginResponse::class);
$this->app->singleton(TwoFactorLoginResponseContract::class, TwoFactorLoginResponse::class);
$this->app->singleton(LogoutResponseContract::class, LogoutResponse::class);
$this->app->singleton(PasswordConfirmedResponseContract::class, PasswordConfirmedResponse::class);
$this->app->singleton(PasswordResetResponseContract::class, PasswordResetResponse::class);
$this->app->singleton(RegisterResponseContract::class, RegisterResponse::class);
$this->app->singleton(SuccessfulPasswordResetLinkRequestResponseContract::class, SuccessfulPasswordResetLinkRequestResponse::class);
}
 
// ...
}

That means every one of these response classes can be overridden in your project if needed!

Jason Beggs photo

TALL stack (Tailwind CSS, Alpine.js, Laravel, and Livewire) consultant and owner of designtotailwind.com.

Cube

Laravel Newsletter

Join 40k+ other developers and never miss out on new tips, tutorials, and more.

image
Acquaint Softtech

Hire Laravel developers with AI expertise at $20/hr. Get started in 48 hours.

Visit Acquaint Softtech
Bacancy logo

Bacancy

Supercharge your project with a seasoned Laravel developer with 4-6 years of experience for just $3200/month. Get 160 hours of dedicated expertise & a risk-free 15-day trial. Schedule a call now!

Bacancy
Tinkerwell logo

Tinkerwell

The must-have code runner for Laravel developers. Tinker with AI, autocompletion and instant feedback on local and production environments.

Tinkerwell
Get expert guidance in a few days with a Laravel code review logo

Get expert guidance in a few days with a Laravel code review

Expert code review! Get clear, practical feedback from two Laravel devs with 10+ years of experience helping teams build better apps.

Get expert guidance in a few days with a Laravel code review
Acquaint Softtech logo

Acquaint Softtech

Acquaint Softtech offers AI-ready Laravel developers who onboard in 48 hours at $3000/Month with no lengthy sales process and a 100 percent money-back guarantee.

Acquaint Softtech
Kirschbaum logo

Kirschbaum

Providing innovation and stability to ensure your web application succeeds.

Kirschbaum
Shift logo

Shift

Running an old Laravel version? Instant, automated Laravel upgrades and code modernization to keep your applications fresh.

Shift
Harpoon: Next generation time tracking and invoicing logo

Harpoon: Next generation time tracking and invoicing

The next generation time-tracking and billing software that helps your agency plan and forecast a profitable future.

Harpoon: Next generation time tracking and invoicing
Lucky Media logo

Lucky Media

Get Lucky Now - the ideal choice for Laravel Development, with over a decade of experience!

Lucky Media
SaaSykit: Laravel SaaS Starter Kit logo

SaaSykit: Laravel SaaS Starter Kit

SaaSykit is a Multi-tenant Laravel SaaS Starter Kit that comes with all features required to run a modern SaaS. Payments, Beautiful Checkout, Admin Panel, User dashboard, Auth, Ready Components, Stats, Blog, Docs and more.

SaaSykit: Laravel SaaS Starter Kit

The latest

View all →
"The Vibes" — NativePHP Hosts a Day 3 after Laracon US image

"The Vibes" — NativePHP Hosts a Day 3 after Laracon US

Read article
What We Know About Laravel 13 image

What We Know About Laravel 13

Read article
New Colors Added in Tailwind CSS v4.2 image

New Colors Added in Tailwind CSS v4.2

Read article
Factory makeMany() Method in Laravel 12.52.0 image

Factory makeMany() Method in Laravel 12.52.0

Read article
Laravel Adds an Official Svelte + Inertia Starter Kit image

Laravel Adds an Official Svelte + Inertia Starter Kit

Read article
MongoDB Vector Search in Laravel: Finding the Unqueryable image

MongoDB Vector Search in Laravel: Finding the Unqueryable

Read article