Laravel Disable CSRF Protection on Specific Routes

CSRF stands for Cross-Site Request Forgery. It is also known as XSRF, Sea Surf, and Session Riding. CSRF is an attack that forces an end user to execute unwanted actions on a web application in which they’re currently authenticated.

Laravel verifies CSRF using VerifyCsrfToken middleware. Here’s the location of the middleware: Illuminate\Foundation\Http\Middleware\VerifyCsrfToke. This middleware gets executed on every HTTP request.

Disable CSRF Protection

To disable CSRF protection, navigate to app\Http\Middleware and open VerifyCsrfToken.php file. We need to add the routes in protected $except = []; array.

Example: I’m going to disable CSRF protection on three routes. The routes are:

routes\web.php
Route::post('route1', 'ExampleController@index1');
Route::post('route2', 'ExampleController@index2');
Route::post('route3', 'ExampleController@index3');

Let’s disable protection on these routes:

app\Http\Middleware\VerifyCsrfToken.php
<?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', 'route3',
    ];
}

The tutorial is over. Thanks for reading.