I want to redirect automatically to my login page when a user session expires using Laravel functions. I do redirect when a user try to access to another page and the session expires. I have set a lifetime which helps to log out automatically because of user's inactivity, and what I want is to redirect instantly when that session timeout.
I tried using JavaScript to timeout but this is not functional when the user is using more than one page at time.
I also tried using AJAX, sending requests to check session status every minute, this works but when the project is in production there's many requests to the server just for checking the session status. (This is the link which helped me for this https://laracasts.com/discuss/channels/laravel/help-is-neededd-on-idle-session-time-out)
Now, I'm trying using App/Exceptions/Handler.php, with the the unauthenticated() function:
protected function unauthenticated($request, AuthenticationException $exception)
{
if ($request->expectsJson()) {
return response()->json(['error' => 'Unauthenticated.'], 401);
}
return redirect()->guest(route('login'));
}
(Redirect User to Login Page When Session Expires - Laravel)
This last solution is not working, no error appears but is doing absolutely nothing.
If is it possible, please tell me the right way to do it.