Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

ahoi's avatar
Level 5

Session expired -> Redirect to / instead of /login

Hello everybody,

I am just wondering, why Laravel is redirecting a user to /login by default if a user's session expires.

Could it be possible to redirect to / instead?

Maybe by changing the ExceptionHandler?

What's best practice here?

0 likes
2 replies
tykus's avatar

Change the redirectTo method in /app/Http/Middleware/Authenticate.php

1 like
maxspbfox's avatar
Level 10

Hello @ahoi . If user's session is expired then user becomes unauthenticated user. And auth middleware comes to play. It checks whether user is authenticated and if not - it throws exception and redirects to login route. Quick solution - to name / end point as login: Route::get('/', '{Controller}@{method}')->name('login')

But I would recommend you to override unauthenticated method in your App\Exceptions\Handler class:

    use Illuminate\Auth\AuthenticationException;    
    
    ...

    protected function unauthenticated($request, AuthenticationException $exception)
    {
        return $request->expectsJson()
            ? response()->json(['message' => $exception->getMessage()], 401)
            : redirect()->guest(route('/'));
    }
1 like

Please or to participate in this conversation.