Laravel comes with a CSRF protection feature. The CSRF stands for Cross-Site Request Forgery. This is one of the major features of Laravel. This feature helps to protect attack that forces end user to execute unwanted actions on a web application in which they’re currently authenticated.
In every form in Laravel, we create a hidden input field with name _token
which will contain a value. This token is used to check CSRF protection in the backend. Thus, no form will work unless a unique token is passed from the frontend form.
CSRF protections is necessary to protect from attackes but sometimes we need to disable it such as while working with the API. For example, if I create an API which is consumed by any frontend client. In such cases, we need to disable the CSRF protection because every client will be unable to submit the token.
We can disable CSRF protection for specific routes by adding the URL to the $except
array inside VerifyCsrfToken
middleware. A basic syntax is given below. In the code below, a route is added inside $except
array. The list of routes inside this array will automatically disable csrf protection.
<?php
namespace App\Http\Middleware;
use Illuminate\Foundation\Http\Middleware\VerifyCsrfToken as Middleware;
class VerifyCsrfToken extends Middleware
{
/**
* The URIs that should be excluded from CSRF verification.
*
* @var array
*/
protected $except = [
'api/*',
'article/*',
'token'
];
}
We can also disable the CSRF protection for all routes using *
inside the array. Note: Please note that it is not a good practice to disable for all routes.
protected $except = [
'*'
];
The process to disable CSRF protection is straight forward. We can add any number of routes in this array. But, keep in mind that only disable the CSRF protection only when necessary because it helps to protect against malicious attacks.