Laravel 8 jetstream stack inertia. Redirect to Home after Login, instead of users choice

18.5k views Asked by At

What happens to me is that if the user puts the url: project.test/med, the system redirects to Login but then it does not redirect to dashboard but to med. In RedirectIfAuthenticated the expression Auth::guard($guard)->check() is not evaluated or at least in the Log it is not shown, so I am not able to identify what is happening.

/** RedirectIfAuthenticated.php */
    public function handle($request, Closure $next, ...$guards)
    {
       $guards = empty($guards) ? [null] : $guards;
       Log::info($request);
       Log::info(Auth::user());
       foreach ($guards as $guard) {
         Log::info(Auth::guard($guard)->check());
         Log::info(Auth::check());
         if (Auth::guard($guard)->check()) {
            return redirect(RouteServiceProvider::HOME);
         }
      }
      Log::info(Auth::check());
      Log::info('end');
      return $next($request);
    }

    /** web.php */
     Route::middleware(['auth:sanctum', 'verified'])->get('/dashboard', function () {
         return Inertia\Inertia::render('Dashboard');
    })->name('dashboard');
    
    Route::middleware(['auth:sanctum','verified'])->get('/med', function (Request $request) {
         return Inertia\Inertia::render('Med');
    })->name('med');
4

There are 4 answers

3
Raphael Cunha On BEST ANSWER

EDIT: Fortify now ships with a simpler way of doing this. See this answer for simplified way.


The RedirectIfAuthenticated middleware does not do what you think it does. This middleware checks to see if a user is authenticated when trying to access a route with the guest middleware attached to it. So after you login to the application and you try to access /login route, this middleware will intercept the request and redirect the user to the RouteServiceProvider::HOME path.


With that being said, at the time of this writing, Laravel Fortify does not offer the ability to easily modify where the user gets redirected after registering or logging in to the application. See issue for more info

To get this to work you will have to go through a few steps.

Step 1 - Create new LoginResponse class

Anywhere in your application create a LoginResponse class and implement Laravel\Fortify\Contracts\LoginResponse.

<?php

namespace App\Http\Responses;

use Laravel\Fortify\Contracts\LoginResponse as LoginResponseContract;

class LoginResponse implements LoginResponseContract
{

    /**
     * @inheritDoc
     */
    public function toResponse($request)
    {
        return $request->wantsJson()
            ? response()->json(['two_factor' => false])
            : redirect()->intended(config('fortify.home')); // This is the line you want to modify so the application behaves the way you want.
    }
}

Step 2 - Override the default Fortify Login Response

In this step you have to tell Laravel to use your login response instead of the default Fortify response.

<?php

namespace App\Providers;

use App\Http\Responses\LoginResponse;
use Illuminate\Support\ServiceProvider;
use Laravel\Fortify\Contracts\LoginResponse as LoginResponseContract;

class FortifyServiceProvider extends ServiceProvider
{
    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        $this->app->bind(
            LoginResponseContract::class, // Contract is required in order to make this step work.
            LoginResponse::class,
        );
    }

    //...
}

Once you're done making the changes the user will be redirected to wherever you set it to be.

2
estern76 On

Go to config/fortify.php and modify this line:

'home' => RouteServiceProvider::HOME,

to:

'home' => function(){
    //if you want to go to a specific route
    return route('dashboard');
  
    //or if you have a bunch of redirection options
    if (Auth::user()->hasRole('admin')) {
       return route('admin.dashboard');
    }
    else{
       return route('guest.dashboard');
    }
}
1
Franck Bokele On

Just open fortify in the config folder

Search for 'home' => RouteServiceProvider::HOME

and replace it but your code logic and don't forget to add Auth facades

use Illuminate\Support\Facades\Auth;

like is :

'home' => function () {
    $is_active = Auth::user()->is_active;
    $role = Auth::user()->role;
   
    if ($is_active == 1) {
        if ($role== 1) {
            return '/admin/dashboard';   
        } else {
            return '/';
        }
    } else {
        return '/login';
    }
},
0
Laurence Rawlings On

There is a simpler solution to this.

If you look in config/fortiy.php you will see the home variable is set to:

'home' => RouteServiceProvider::HOME,

This refers to a public const variable in app/Providers/RouteServiceProvider.php

So to redirect users to the home page after they login you can simply change the home variable:

public const HOME = '/';

Doing it this way is slightly less complex and saves you having to create a whole new login response class.

If the changes don't take effect straight away try running:

php artisan optimize