The TokenMismatchException in Laravel can be extremely tricky to solve and can take a fair amount of time.
Here is a quick step by step check list guide of how to solve the following exception throws in "TokenMismatchException in VerifyCsrfToken" in Laravel 5:
-
Check you have set a _token value csrf_field(), or csrf_token() in the form you are sending.
-
Check you are actually sending the field
-
If using Ajax.
First. Set a meta field with the token.
Second. Then set it to be used globally:
`$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content');
}
});`
- If using XEditable you may first set it a meta field like the example above, then use like this:
`var token = $('meta[name="csrf-token"]').attr('content');`
$('#myaccount-name').editable({
type: 'text',
title: 'Enter new name',
params: {_token:token},
});
-
Check your sessions are working. If not make sure your "storage" and "bootstrap/cache" directories are writable by the web user. You can use the script from here http://lesichkov.co.uk/article/20151113080209452243/laravel-fix
-
Check you are not sending more variables than the option "max_input_vars" set in your "php.ini" file. If so you have two options: increase the "max_input_vars" and restart the server, or decrease the form variables.
-
If you are using Ajax and it is ok from security point of view, you may want to disable CSRF for the specific route.
-
Check the server date time settings are correct and synchronized. Then check your Laravel config has the correct time zone.
-
Empty the Laravel sessions directory "/storage/framework/sessions" and cache. Then clear your browser cookies and cache, restart your browser. Check with a different broser.
-
Make sure your cookies are set to the root of the domain, and that the domain itseld is correct;
`'path' => '/',`
- Very edge case described here: https://stackoverflow.com/questions/30490821/laravel-5-tokenmismatchexception-on-php-5-6-9/30508294#30508294
`public function handle($request, Closure $next) {
$response = $next($request);`
if (last(explode('\\',get_class($response))) != 'RedirectResponse') {
$response->header('P3P', 'CP="IDC DSP COR ADM DEVi TAIi PSA PSD IVAi IVDi CONi HIS OUR IND CNT"');
}
return $response;
}
The above check list should fix your issues with this "TokenMismatchException in VerifyCsrfToken" thrown in Laravel 5.
Thank you.