Laravel Idea for PhpStorm - Full-featured IDE for productive artisans!

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.

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
Lucky Media logo

Lucky Media

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

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
LaraJobs logo

LaraJobs

The official Laravel job board

LaraJobs
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
Rector logo

Rector

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

Rector
MongoDB logo

MongoDB

Enhance your PHP applications with the powerful integration of MongoDB and Laravel, empowering developers to build applications with ease and efficiency. Support transactional, search, analytics and mobile use cases while using the familiar Eloquent APIs. Discover how MongoDB's flexible, modern database can transform your Laravel applications.

MongoDB

The latest

View all →
API Platform for Laravel image

API Platform for Laravel

Read article
Pan - A simple, lightweight, and privacy-focused product analytics php package image

Pan - A simple, lightweight, and privacy-focused product analytics php package

Read article
The Inertia.js v2 Beta is Here image

The Inertia.js v2 Beta is Here

Read article
Mastering Laravel, No Compromises, and SourceDive with Joel Clermont image

Mastering Laravel, No Compromises, and SourceDive with Joel Clermont

Read article
Now you can install PHP and the Laravel installer with a single command image

Now you can install PHP and the Laravel installer with a single command

Read article
WireSpy is a Sleek New Debug Bar for Laravel Livewire image

WireSpy is a Sleek New Debug Bar for Laravel Livewire

Read article