Home >Backend Development >PHP Tutorial >How to Resolve 419 Status Code for POST and PUT Methods in Laravel Due to CSRF Protection?
When attempting to develop RESTful APIs using Laravel, you may encounter a 419 status code on POST and PUT methods. This issue stems from Laravel's CSRF protection, which aims to prevent cross-site request forgery (CSRF) attacks.
Laravel's web.php routes are protected by CSRF tokens by default. CSRF tokens are a way to ensure that a request is coming from a legitimate source and not from a malicious user. When POST or PUT requests do not contain the correct CSRF token, Laravel returns a 419 status code.
If you are using web.php routes for API endpoints, you can exclude them from CSRF protection by adding them to the $except property of the VerifyCsrfToken middleware.
<code class="php">namespace App\Http\Middleware; use Illuminate\Foundation\Http\Middleware\VerifyCsrfToken as BaseVerifier; class VerifyCsrfToken extends BaseVerifier { /** * The URIs that should be excluded from CSRF verification. * * @var array */ protected $except = [ 'api/*', // Exclude all API routes from CSRF protection ]; }</code>
If you are using Laravel version 5.4 or higher, it is recommended to use the api.php file for API routes. Routes defined in api.php are automatically excluded from CSRF protection.
You can disable CSRF protection for specific methods within a route group.
<code class="php">Route::group(['middleware' => ['api', 'without_csrf_token']], function () { Route::post('/store', 'RestController@store'); Route::put('/update/{id}', 'RestController@update'); });</code>
By excluding routes from CSRF protection or disabling it for specific methods, you can resolve the 419 status code issue. Remember to only disable CSRF protection when necessary, as it is an important security measure for user-submitted forms.
The above is the detailed content of How to Resolve 419 Status Code for POST and PUT Methods in Laravel Due to CSRF Protection?. For more information, please follow other related articles on the PHP Chinese website!