I recently migrated to Laravel 5, and now CSRF check is on every post submission. I thought about removing it but I want to follow the best practices, so I\'ll keep it that
You need to pass along the header X-XSRF-TOKEN
which contains an encrypted version of the csrf-token
.
There are two ways which this can be done that I am aware of. You can encrypt the token and pass it along to the view:
$xsrfToken = app('Illuminate\Encryption\Encrypter')->encrypt(csrf_token());
return view('some.ajax.form.view')->with('xsrf_token', $xsrfToken);
Or you can grab the token from cookies using JavaScript (Angular makes this easy). In vanilla JS you might do something like this:
function getCookie(name) {
var pattern = RegExp(name + "=.[^;]*")
matched = document.cookie.match(pattern)
if (matched) {
var cookie = matched[0].split('=')
return decodeURIComponent(cookie[1])
}
return false
}
In jQuery you might then do something like this for the ajax request:
$.ajax({
// your request
//
beforeSend: function(request) {
return request.setRequestHeader('X-XSRF-TOKEN', getCookie('XSRF-TOKEN'));
}
});