I think you can solve this as follows:
- Display the token on some attribute of a DOM element
- Capture this value of the DOM token in each ajax request and send it as the
_token
value.
Then, it could be done something like this:
<body data-token="{{ csrf_token() }}"></body>
In ajax:
$.ajax({
data: {..., _token: $('body').data('token') }
});
Another way to configure your ajax requests (and I believe that is the most viable) is to use the $.ajaxSetup
function, so that all requests inherit the header with the token. So:
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('body').data('token')
}
});
In the VerifyCsrfToken.php
file, you will need to add this method:
protected function tokensMatch($request)
{
if ($request->ajax()) {
$token = $request->input('_token');
} else {
$token = $request->header('X-CSRF-Token');
}
return $request->session()->token() == $token;
}
Disabling Token
If you want to disable token checking on ajax requests (which I do not consider to be unsafe), you can do the following:
protected function tokensMatch($request)
{
if ($request->ajax()) return true;
return $request->session()->token() == $token;
}