Reputation: 4232
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
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
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