If you have seen a TokenMismatchException
in your Laravel application. You have a CSRF token mismatch issue. A TokenMismatchException
exception indicates that the CSRF token sent from the frontend failed the backend validation.
The number one reason of CSRF token issue is missing of the _token
input field in your form page.
To fix this, simply add the @csrf
field to your existing form:
<form>
@csrf
</form>
If you are seeing the exception in an ajax page. It might be that you missed to send CSRF token in your Ajax call.
If you are sending an ajax call, you will need to send along the CSRF token.
In the head
section of the HTML page, render the CSRF token:
<head>
...
<meta name="csrf-token" content="{{ csrf_token() }}">
...
</head>
Then in your Ajax call, attach the CSRF token:
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
If you want to change the exception message, you can do so by following the steps below:
app/Exceptions/Handler.php
prepareException
method as shown below:protected function prepareException(Exception $e)
{
if ($e instanceof TokenMismatchException) {
$e = new HttpException(419, 'Your session has expired. Please refresh the page to continue using the system.', $e);
}
return parent::prepareException($e);
}
Sometimes, you might want completely avoid CSRF validation in some pages. For example, a logout page does not require a CSRF protection.
You can avoid CSRF protection for pages by modifying the app/Http/Middleware/VerifyCsrfToken.php
file.
<?php
namespace App\Http\Middleware;
use Illuminate\Foundation\Http\Middleware\VerifyCsrfToken as Middleware;
class VerifyCsrfToken extends Middleware
{
/**
* The URIs that should be excluded from CSRF verification.
*
* @var array
*/
protected $except = [
//
];
}
Add the routes that do not require CSRF protection to the $except
:
protected $except = [
'/logout'
];
That is all for this tutorial and we have covered most of cases of fixing CSRF token mismatch exception in Laravel 9.