title: Redirect automatically when user session expires in Laravel 5.5
body: <p>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. </p>
  
  <p>I tried using JavaScript to timeout but this is not functional when the user is using more than one page at time.</p>
  
  <p>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 <a href="https://laracasts.com/discuss/channels/laravel/help-is-neededd-on-idle-session-time-out" rel="nofollow noreferrer">https://laracasts.com/discuss/channels/laravel/help-is-neededd-on-idle-session-time-out</a>)</p>
  
  <p>Now, I'm trying using <strong>App/Exceptions/Handler.php</strong>, with the the <strong>unauthenticated()</strong> function: </p>
  
  <pre><code>protected function unauthenticated($request, AuthenticationException $exception)
  {
    if ($request-&gt;expectsJson()) {
          return response()-&gt;json(['error' =&gt; 'Unauthenticated.'], 401);
      }
  
      return redirect()-&gt;guest(route('login'));
  }
  </code></pre>
  
  <p>(<a href="https://stackoverflow.com/questions/47274200/redirect-user-to-login-page-when-session-expires-laravel">Redirect User to Login Page When Session Expires - Laravel</a>)</p>
  
  <p>This last solution is not working, no error appears but is doing absolutely nothing.</p>
  
  <p>If is it possible, please tell me the right way to do it.</p>