How to handle an expired CSRF token nicely in Laravel

Tip published on November 19, 2016 by @markvaneijk in Laravel

Laravel throws an exception when the CSRF token in the form does not match the token saved in the session of a user for increased security and to prevent users to submit any data from remote servers to your website.

The exception however can come up for a number of reasons, but the most important will be when the token has expired or there's a mismatch. It's also possible that the user left a browser tab with your web app open and decided to finish it later. Because of the CSRF token, which can expire, this will fail following an exception.

To make your app handle this situation more user friendly, we can change the way Laravel treats this situations. Here's how you do it:

Place the following code in the app/Exceptions/Handler.php file, to gracefully show an error message above your forms when the CSRF token is expired.

<?php

public function render($request, Exception $exception)
{
    if ($exception instanceof \Illuminate\Session\TokenMismatchException) {
        return back()
               ->withInput($request->except('password'))
               ->withErrors('Your session timed out, please submit the form again.');
    }

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

Now whenever a user sends a form with and expired token, the user will still have all it's input fields filled in because of the redirect with all the input of the form fields. Also the user gets a nice error message which indicates what's wrong.