How to disable CSRF Token in Laravel and why we have to disable it?

I want to see how I can disable CSRF token in Laravel and where I have to disable it. Is this good to disable it or not?


You can Disable CSRF on few routes by editing.

App\Http\Middleware\VerifyCsrfToken 

and add your own routes name in protected

$except = [] array.

It does not seems to be good practice as by doing this we are removing security feature of Laravel.


Many people explain how to do it, but they do not explain what the url should look like.

edit app/Http/Middleware/VerifyCsrfToken.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 = [
        '/user/my_function'
    ];
}

In the $except array(); we add a url with just a simple string. This points to a controller usually depending on how your route is setup.

For example I have a UserController.php file in my Controller folder. I have a route like. In the web.php routes file.

Route::post('/user', 'UserController@my_function')->name('my_function');

Also alternatively, if you came to this question simply because you don't know how to use the CSRF and you don't actually need to disable it, or make the URL except. You can use this method.

Add these lines to your app.blade.php if it is used for ajax related calls.

<script>
$(function() {
    $.ajaxSetup({
        headers: {
        'X-CSRF-Token': $('meta[name="csrf-token"]').attr('content')
        }
    });
});
</script>

In laravel 7. Open file \App\Http\Middleware\VerifyCsrfToken.php

Disable for all routes

protected $except = [
    '*',
];

Disable for some routes

 protected $except = [
    'mobile/*',
    'news/articles',
];

I searched for a long time how to disable CSRF completely, there are many identical examples but they do not help