CSRF Token not working in Laravel 5.1 Exceptions Handler with an Ajax request
<p>I have a Laravel 5.1 application with Ajax content loaded at start up.</p>

<p>I have placed the CSRF meta tag to page head:</p>

<pre><code>&lt;meta name="csrf-token" content="{{ csrf_token() }}" /&gt;
</code></pre>

<p>And I use it in jquery ajax requests:</p>

<pre><code>$.ajaxSetup(
{
  headers:
  {
    "X-CSRF-TOKEN": $('meta[name="csrf-token"]').attr("content")
  }
});
</code></pre>

<p>Everything works perfectly under normal circumstances. But when I open a 404 error page without a previous session, my ajax requests get an error:
TokenMismatchException in VerifyCsrfToken.php</p>

<p>I have an 404 error handler in file: app\Exceptions\Handler.php</p>

<pre><code>public function render($request, Exception $e)
{
  if ($e instanceof NotFoundHttpException)
  {
    $foo = \App\Foo::foo();
    return \Response::make(view("errors.404", compact("foo")), 404);
  }

  return parent::render($request, $e);
}
</code></pre>

<p>I can repeat this error by opening a private browser window and opening my site with an url to a non existing page. It persists on page reloads. But if I go to an existing page and try the 404 url again, it works fine.</p>

<p>Any ideas how fix this problem?</p>

<p>EDIT:</p>

<p>I tried checking multiple ajax requests and it seems like every request has a complitely different session with different token:</p>

<pre><code>$request-&gt;session()-&gt;token();
</code></pre>