Redirect back to previous page after login with Laravel Fortify

May 21st, 2023

Laravel Fortify authentication creates all the backend for authentication - routes, controllers needed for login, register, password reset, 2factor login, email verification,... All the front end is up to you.

In basic Laravel Breeze authentication you would put your logic for redirecting back to previous page to LoginController, but with Laravel Fortify authentication, we don't have a LoginController, so we can't put logic there.

Laravel Fortify uses Laravel\Fortify\Contracts\LoginResponse for authentication, so we will create our own LoginResponse, which will override Fortify's LoginResponse.

We can't just redirect back or to url previous, because previous url is /login url, which by default redirects to /home page as defined in RouteServiceProvider.

We have to get url that is previous to login page, put it in session and then after successful login, we redirect to url that we stored in session.

  • FortifyServiceProvider.php

If session doesn't have link, then put url()->previous() to session link

1 Fortify::loginView(function() {
2 // dd(url()->previous());
3 if(!session()->has('link')){
4 session(['link' => url()->previous()]);
5 }
6 
7 return view('auth/login');
8});
  • App\Http\Responses\LoginResponse.php

redirect to link stored in session

1<?php
2 
3namespace App\Http\Responses;
4 
5use Laravel\Fortify\Contracts\LoginResponse as LoginResponseContract;
6 
7class LoginResponse implements LoginResponseContract
8{
9 public function toResponse($request)
10 {
11 return redirect(session()->get('link'));
12 }
13}