LARAVEL: How to redirect users on timeout

Gabriel Guerra
Mar 9 · 2 min read

Sometimes web frameworks leads us to weird scenarios.

For a protected area, it's common and expected that every session have an inactivity period set and, after that, the user is forced to log in again. Well, Laravel doesn't have a default redirect url for this situation except the infamous screen message:

We can handle that :)

Redirecting users when timeout occurs is easy. Timeout triggers an Exception which can be caught and treated accordingly our needs.

Photo credits & licensing

Laravel has a Handler with this sole purpose.

What we're going to do is just edit the Exceptions handler in App/Exceptions/Handler.php

In the render method add the following:

if ($exception instanceof AuthenticationException) {
return redirect('/');
}

The whole method will become like this:

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

That’s it. Happy coding!


Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade