How To Get And Use CSRF Token in Laravel?

Laravel automatically generates a CSRF “token” for each user session. It is stored in user’s session so any malicious request can be blocked. Laravel implements this using a middleware called VerifyCsrfToken.php. Here is the code which you will see in it.

app/Http/Middleware/VerifyCsrfToken.php

<?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 = [
        //
    ];
}

Now as we know every request must have _token into it like filling a form, ajax request and post request etc. So here are all the ways to implement this so that you can get away from Token mismatch exception.

1. Submitting a form

So while submitting a form we need to put this line in our blade file in between form tag.

@csrf

That’s it. It will add hidden field with the name _token in your form. Here is the example code.

<form method="POST" action="{{ route('some-route') }}">
    @csrf
    <input name="email" type="text">
    <input name="name" type="text">
</form>

We can use this function as well.

{{ csrf_field() }}

2. Using JavaScript or jQuery

Laravel add meta tag in every page which have updated CSRF token. We can access that while sending ajax or JS request to the server. That’s super easy.

var csrf = document.querySelector('meta[name="csrf-token"]').content;

and for jQuery Ajax use this code.

var csrf = document.querySelector('meta[name="csrf-token"]').content;
    $.ajax({
        url: 'your-url',
        type: "POST",
        data: { 'value': value, '_token': csrf },
        success: function (response) {
            console.log(response);
        }
    });

3. Using CSRF for all forms and Ajax requests

For every form and every Ajax request just put this in your code in your JS file which is running across the site on every page. It is an easy hack.

var csrf = document.querySelector('meta[name="csrf-token"]').content;
var csrf_field = '<input type="hidden" name="_token" value=“'+csrf+'”>';

$('form').append(csrf_field);

$.ajaxSetup({
    beforeSend: function (xhr, settings) {
        if (settings.url.indexOf(document.domain) >= 0) {
            xhr.setRequestHeader("X-CSRF-Token", csrf);
        }
    }
});

4. Disabling CSRF Token

You should never do that otherwise your site could be hacked but if in case you need to disable it anyway then use this method. It is the most safe. In app/Http/Middleware/VerifyCsrfToken.php  file you will see this code.

<?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 = [
        //
    ];
}

Now change $except property like this.

<span class="hljs-keyword">protected</span> <span class="hljs-variable">$except</span> = [
    <span class="hljs-string">'mobile/*'</span>,
    <span class="hljs-string">'news/articles'</span>,
];

And this is highly dangerous but if you want to disable CSRF for all requests then use this.

protected $except = [
    '*',
];

Again this is not recommended and very dangerous. I hope you learned everything about CSRF token. If you have any questions please leave a comment.