I have analyze that ratio of getting Token Mismatch Error is very high. And this error getting because of some of the silly mistakes. There are many reasons developers are doing mistakes. Here are some of the examples.
- Not sending
_token
on header. - Not sending
_token
on data when using ajax. - Not Permission on Storage Path.
- Invalid Session Storage path.
And there many other reasons, feel free to edit this question for more more ways to prevent this type of error.
Possible Change - 1
Setup Token on Header
Set the token on
<head>
of yourdefault.blade.php
viewAdd
ajaxSetup
on the top of your script, that will be accessible to everywhere. This will set headers on each ajax callSet Token on
<form>
tagAdd below function to your
<form>
tag. This function will generate a hidden field named_token
and filled value with tokenAdd
csrf_token()
function to your hidden_token
in value attribute. This will generate only encrypted string.<input type="hidden" name="_token" value="{{csrf_token()}}"/>
.Possible Change - 2
Check session storage path & Permission
Here assume that project app url is
APP_URL=http://project.dev/ts/toys-store
storage_path('framework/sessions')
'path' => '/ts/toys-store',
this path is root of your laravel project.Change the name of your cookie
'cookie' => 'toys-store',
Possible Change - 3
Use
_token
field on AJAXThere are many ways to send
_token
on AJAX call<form>
tag usingvar formData = new FormData($("#cart-add")[0]);
$("#cart-add").serialize();
or$("#cart-add").serializeArray();
_token
manually on data of AJAX. using$('meta[name="csrf-token"]').attr('content')
or$('input[name="_token"]').val()
.We can set as header on a particular ajax call like below code.