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 roasted.dev.

Cube

Laravel Newsletter

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

image
DocuWriter.ai

Save hours of manually writing Code Documentation, Comments & DocBlocks, Test suites and Refactoring.

Visit DocuWriter.ai
Laravel Forge logo

Laravel Forge

Easily create and manage your servers and deploy your Laravel applications in seconds.

Laravel Forge
Tinkerwell logo

Tinkerwell

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

Tinkerwell
No Compromises logo

No Compromises

Joel and Aaron, the two seasoned devs from the No Compromises podcast, are now available to hire for your Laravel project. ⬧ Flat rate of $7500/mo. ⬧ No lengthy sales process. ⬧ No contracts. ⬧ 100% money back guarantee.

No Compromises
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
Bacancy logo

Bacancy

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

Bacancy
LoadForge logo

LoadForge

Easy, affordable load testing and stress tests for websites, APIs and databases.

LoadForge
Paragraph logo

Paragraph

Manage your Laravel app as if it was a CMS – edit any text on any page or in any email without touching Blade or language files.

Paragraph
Lucky Media logo

Lucky Media

Bespoke software solutions built for your business. We ♥ Laravel

Lucky Media
Lunar: Laravel E-Commerce logo

Lunar: Laravel E-Commerce

E-Commerce for Laravel. An open-source package that brings the power of modern headless e-commerce functionality to Laravel.

Lunar: Laravel E-Commerce
DocuWriter.ai logo

DocuWriter.ai

Save hours of manually writing Code Documentation, Comments & DocBlocks, Test suites and Refactoring.

DocuWriter.ai
Rector logo

Rector

Your partner for seamless Laravel upgrades, cutting costs, and accelerating innovation for successful companies

Rector

The latest

View all →
Generate Code Coverage in Laravel With PCOV image

Generate Code Coverage in Laravel With PCOV

Read article
Non-backed Enums in Database Queries and a withSchedule() bootstrap method in Laravel 11.1 image

Non-backed Enums in Database Queries and a withSchedule() bootstrap method in Laravel 11.1

Read article
Laravel Pint --bail Flag image

Laravel Pint --bail Flag

Read article
Laravel Herd for Windows is now released! image

Laravel Herd for Windows is now released!

Read article
The Laravel Worldwide Meetup is Today image

The Laravel Worldwide Meetup is Today

Read article
Cache Routes with Cloudflare in Laravel image

Cache Routes with Cloudflare in Laravel

Read article