Laravel

How to protect or prevent your site/forms against CSRF in laravel

It’s really easy to automatically protect your forms in Laravel for Cross-site Request Forgery (CSRF). I will show you how this can be done automatically for all your Laravel applications.

CSRF

When creating a form using the Form class, Laravel injects automatically a hidden input with a token in the HTML of the form. This token can be used by Laravel to validate with a token from a server session to make sure the request comes from your own application. But as for now Laravel does not check automatically for this CSRF token when sending a form. So we need to do this our selves.



If you’re not using the Form class, you’ll need to write manually a Form::token() in your form.

Using the documentation of Laravel checking for the CSRF token can be done using filters in routes or your controllers. But this is not super DRY as we want it to be. Here’s how it is done in a super DRY way:

Place this code in the app/routes.php file, to let Laravel filter automatically every request for the CSRF token.

This will check for a POST, PUT or DELETE request and if so, it will automatically use the already existing CSRF filter in Laravel.

And that’s it! Protecting your forms against CSRF was never this easy!