I believe that you can solve this in the following way:
- Display the token in an attribute of a DOM element
- Capture this DOM token value in each ajax request and send it as the value
_token
.
So it could be done more or less 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 think it’s the most feasible) is by using the function $.ajaxSetup
, for all requests to inherit the header with the token. So:
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('body').data('token')
}
});
In the archive VerifyCsrfToken.php
, 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 the Token
If you want to disable token checking on ajax requests (which I don’t consider anything safe), you can do it as follows:
protected function tokensMatch($request)
{
if ($request->ajax()) return true;
return $request->session()->token() == $token;
}
yes I already knew about it. in the documentation of Laravel has this information.
– LeandroLuk