title: How to prevent the TokenMismatchException reliably during Ajax calls in Laravel?
body: <p>I know there have been many questions asked before about handling the CSRF token on Ajax calls in Laravel. The Laravel docs <strong><a href="https://laravel.com/docs/5.2/routing#csrf-x-csrf-token" rel="nofollow noreferrer">specify a way</a></strong> to pass the csrf_token value on any Ajax request like this:</p>
  
  <pre><code>$.ajaxSetup({
          headers: {
              'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
          }
  });
  </code></pre>
  
  <p>and <strong>this is exactly what I'm doing</strong> in my app.</p>
  
  <p>However, there are still plenty of cases when the <code>TokenMismatchException</code> gets thrown and logged on the server. I think one reason for this is the following:</p>
  
  <ol>
  <li>User loads a page and leaves the page open </li>
  <li>Laravel session expires    </li>
  <li>The user gets back to the PC and triggers an Ajax call (e.g. by clicking on a button)</li>
  <li>The Ajax call gathers the <code>csrf-token</code> value from the meta tag</li>
  </ol>
  
  <p>Now, the <code>csrf-token</code> value passed wth the call is, of course, wrong now, as Laravel session doesn't exist and needs to be regenerated.</p>
  
  <p>Laravel docs also <strong><a href="https://laravel.com/docs/5.2/routing#csrf-x-xsrf-token" rel="nofollow noreferrer">suggests</a></strong> using the <code>XSRF-TOKEN</code> cookie. However, the cookie has - obviously - the same expiration date as the <code>laravel_session</code> cookie, which won't help me either.</p>
  
  <p>Notice that the user doesn't necessarily have to be authenticated to generate Ajax calls, they can be fired by guest users, and all are checked against cross-site request forgery.</p>
  
  <p><strong>Is there a way to get around this and prevent the <code>TokenMismatchException</code> in situations like I described above?</strong></p>
  
  <p>Sidenote:</p>
  
  <p>The case I described is probably not the only one. The exception's been thrown and logged 36 times in the past 24 hours, and I'm sure those occurrences cannot all be linked the same issue, especially as these are various Ajax calls - both GET and POST.</p>