php – What is the use of csrf_token present in Laravel's layout file?


I am aware that to submit a form in Laravel, you need to add a csrf_field, or declare that the route should bypass this protection. However, in the layout file there are the following occurrences:

<meta name="csrf-token" content="{{ csrf_token() }}">


    window.Laravel = {!! json_encode([
        'csrfToken' => csrf_token(),
    ]) !!};

What are these blocks mentioned above used for?


This is more specifically intended for forms of the AJAX type. It's basically taking the token and including it in the headers for when you send a request via AJAX .

Laravel automatically generates a token CSRF for each active user session managed by the application. This token is used to verify that the authenticated user is the one who actually makes requests to the application.

In addition to verifying the token CSRF as a POST parameter, the VerifyCsrfToken middleware also verifies the request header ( X-CSRF-TOKEN ). Hence the existence of this metatag .

<meta name="csrf-token" content="{{ csrf_token() }}">

Then, once you've created the meta tag, you can instruct a library like jQuery to automatically add the token to all request headers. This provides simple and convenient CSRF protection for your AJAX-based applications:

    headers: {
        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
Scroll to Top