zwl1619
zwl1619

Reputation: 4232

Laravel 5.4.30 : How to get csrfToken?

How to get csrfToken in Laravel 5.4.30 ?

In older version, There is a piece of code like this:

   <script>
        window.Laravel = <?php echo json_encode([
            'csrfToken' => csrf_token(),
        ]); ?>
    </script>

So, I could get csrfToken in javascript like this:

Laravel.csrfToken

Now I update laravel to 5.4.30,the code above has been moved,and in bootstarp.js,there is a piece of code like this:

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

Quesion:
How to get csrfToken in javascript now ?

Upvotes: 0

Views: 1272

Answers (3)

AddWeb Solution Pvt Ltd
AddWeb Solution Pvt Ltd

Reputation: 21681

You should tr this:

1. add tag with the token to the blade layout:

<meta name="_token" content="{{ csrf_token() }}">

2. setup ajax requests:

$(function() {
  $.ajaxSetup({
    headers: {
      'X-CSRF-Token': $('meta[name="_token"]').attr('content')
    }
  });
});

Upvotes: 3

Leonardo Cabr&#233;
Leonardo Cabr&#233;

Reputation: 1235

if you need it for ajax calls, you can try this:

$.ajaxSetup({
    headers: {
        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
    }
});

and in the head of you blade:

<meta name="csrf-token" content="{!! Session::token() !!}">

Upvotes: 0

Kuldeep Mishra
Kuldeep Mishra

Reputation: 4040

{{ csrf_token() }}
 or
{{ csrf_field() }}

Upvotes: 1

Related Questions