Site icon Web Niraj

Laravel 5.x: Redirect CSRF Errors to Previous Page

I have always found it frustrating that failing the CSRF check in Laravel 5.x throws an exception. I would rather prefer it redirect the user back to the previous page, and get them to try again. So, I modified the VerifyCsrfToken.php middleware to do just that, in just a few lines of code.

In the VerifyCsrfToken.php (found in folder App\Http\Middleware), I added the handle function that overwrites the default Laravel behaviour when the CSRF check fails. If this file doesn’t exist in your installation, the full code is included below:

See the gist on github.

On lines 22-29, I make sure unit tests, successful CSRF checks and pages that are excluded work as they should (this was taken from the original Illuminate\Foundation\Http\Middleware\VerifyCsrfToken class).

On line 32, instead of throwing the TokenMismatchException exception, I use the Redirect facade to redirect the user back to the previous page, and display an error.

Note: Remember to include the use statement for both the Closure and Redirect facades (see lines 5-6), or you will get exceptions when running your code.

Next time the CSRF check fails, your users will get a better looking error message and the chance to retry. Here is an example of how it looks on the login page:

Exit mobile version