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

linktoahref's avatar

Redirect to Custom URL after session timeout

I have an route '/admin' which is using the auth middleware.

Once the session is timed out while accessing the route it redirects to the default '/login' route. I would like to redirect the user to '/' instead.

Where and what changes should I make? I'm using Laravel 5.5

0 likes
7 replies
RamjithAp's avatar
Level 10

For laravel version < 5.5 go to App/Exceptions/handler.php and change this method

protected function unauthenticated($request, AuthenticationException $exception)
{
    if ($request->expectsJson()) {
        return response()->json(['error' => 'Unauthenticated.'], 401);
    }

    return redirect()->guest(route('/'));
}

For laravel 5.5 App/Exceptions/handler.php

<?php
    namespace App\Exceptions;
    use Exception;
    use Request;
    use Illuminate\Auth\AuthenticationException;
    use Response;
    use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
    class Handler extends ExceptionHandler
    {

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

Hello

How can I do the same thing in Laravel 8? i.e. How can redirect to e.g lsyt/login after the authenticated user session expired. I didn't find this redirect()->guest(route('/')); in App/Exceptions/handler.php. in Laravel 8. Please help.

Thanks.

1 like
linktoahref's avatar

Thank You @RamjithAp

I just edited app/Exceptions/Handler.php and doing a check like

public function render($request, Exception $exception)
{
    if ($exception instanceof AuthenticationException) {
        return redirect('/');
    }
    return parent::render($request, $exception);
}

and doing necessary imports like use Illuminate\Auth\AuthenticationException as AuthenticationException;

resolved the issue.

RamjithAp's avatar

However, That's not the recommended way when there is unauthenticated() method available for this purpose.

1 like
jovennovo2017's avatar

Thank you for having the same problem with you linktoahref, it also solved my problem.

Please or to participate in this conversation.