twitter github codepen dribbble rss

Handling Laravel CSRF Token Mistmatch Exception

To protects your website from cross-site request forgery (CSRF) attacks, Laravel automatically generates CSRF token for each active user session. That token will then be verified by VerifyCsrfToken middleware whenever user submits the form.

It will throw TokenMismatchException error if CSRF token is expired or doesn’t match. That’s why sometimes you see this error when you submit form in your website. Especially when the form is sitting long enough letting the CSRF token expires.

csrf token mismatch exception

That error will surely confuse your users, so you should handle that. Thankfully, in Laravel 5.5, the exception is already handled by default. Now, it will be showing this custom error page instead.

csrf-token mismatch exception error

You can customize the error page by creating 419.blade.php template file in resources/views/errors/ folder.

That’s great, but there is one drawback which is all the form data that your users input are gone now because the page need to be refreshed and users must input their data all over again.

So, we need to handle the exception ourselves then. How?

  1. All of your exceptions are handled in file : app\Exceptions\Handlers.php.
  2. Open that file and look for render function. In this function, you can filter the exceptions and handle them accordingly.
  3. So, if the exception is TokenMismatchException we need to refresh the token by going back to form view (using redirect()->back()).
  4. Then we flash the input data and error message, so that we can repopulate input data back to the form.
  5. It should be like this :
public function render($request, Exception $exception)
{
   if ($exception instanceof \Illuminate\Session\TokenMismatchException) {
       return redirect()
              ->back()
              ->withInput($request->except(['password', 'password_confirmation']))
              ->with('error', 'The form has expired due to inactivity. Please try again');
   }

   return parent::render($request, $exception);
}

In your form view, don’t forget to show the error message to the users.

@if (session('error'))
    <div class="alert alert-danger" role="alert">{{ session('error') }}</div>
@endif

This is the example for that. Users are informed that the need to submit the form again, but their data are still there so that they don’t need to input their data again.

handling csrf token mismatch exception