If for some reason you need to disable the CSRF token protection on your routes, this is very easy to do, for specific routes, just add specific routes in VerifyCsrfToken.php
file and for all routes, you need to remove or comment out VerifyCsrfToken::class
from the kernel.php
file.
Laravel disable CSRF token protection example. In this Laravel tutorial, we will learn how to disable CSRF token protection on all routes (web and api) and specific routes in laravel apps.
How to Disable CSRF Token Protection on Routes in Laravel
Here are some options on how to disable CSRF token protection for all routes (web and API) and specific routes:
Option 1: Laravel Disable CSRF Protection All Routes
To disable CSRF token protection on all (web, api & other) routes in laravel, Simply Navigate to app/HTTP/ directory, Open Kernal.php file, and remove or comment out this line \App\Http\Middleware\VerifyCsrfToken::class
from app\Http\Kernel.php
file; as follows:
protected $middlewareGroups = [ 'web' => [ \App\Http\Middleware\EncryptCookies::class, \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class, \Illuminate\Session\Middleware\StartSession::class, // \Illuminate\Session\Middleware\AuthenticateSession::class, \Illuminate\View\Middleware\ShareErrorsFromSession::class, //\App\Http\Middleware\VerifyCsrfToken::class, \Illuminate\Routing\Middleware\SubstituteBindings::class, ], ];
Option 2: Laravel Disable CSRF Protection on Specific Routes
Navigate to app\Http\Middleware
and open VerifyCsrfToken.php
file, and add a specific route url in protected $except = ['route1', 'route2'];
array to disable CSRF protection for specific routes in laravel; is as follows:
<?php namespace App\Http\Middleware; use Illuminate\Foundation\Http\Middleware\VerifyCsrfToken as Middleware; class VerifyCsrfToken extends Middleware { /** * Indicates whether the XSRF-TOKEN cookie should be set on the response. * * @var bool */ protected $addHttpCookie = true; /** * The URIs that should be excluded from CSRF verification. * * @var array */ protected $except = ['route1', 'route2']; }
Conclusion
In this tutorial, we have learned how to disable csrf token protection for all routes or specific routes in laravel apps.