Set the token on <head>
of your default.blade.php
.
<meta name="csrf-token" content="{{csrf_token()}}">
Add ajaxSetup
on the top of your script, that will be accessible to everywhere. This will set headers on each ajax
call
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
Add below function to your <form>
tag. This function will generate a hidden field named _token
and filled value with the token.
{{csrf_field()}}
Add csrf_token ()
function to your hidden _token
in the value attribute. This will generate only encrypted string.
<input type="hidden" name="_token" value="{{csrf_token()}}"/>
.
Here I assume that project app url is APP_URL=http://project.dev/ts/toys-store
storage_path('framework/sessions')
the folder.'path' => '/ts/toys-store',
the root of your laravel project.'cookie' => 'toys-store',
return [
'driver' => env('SESSION_DRIVER', 'file'),
'lifetime' => 120,
'expire_on_close' => false,
'encrypt' => false,
'files' => storage_path('framework/sessions'),
'connection' => null,
'table' => 'sessions',
'lottery' => [2, 100],
'cookie' => 'toys-store',
'path' => '/ts/toys-store',
'domain' => null,
'secure' => false,
'http_only' => true,
];
There are many ways to send _token
on AJAX call
<form>
tag using var formData = new FormData($("#cart-add")[0]);
$("form").serialize();
or $("form").serializeArray();
_token
manually on data
of Ajax. using $('meta[name="csrf-token"]').attr('content')
or $('input[name="_token"]').val()
.$.ajax({
url: $("#category-add").attr("action"),
type: "POST",
data: formData,
processData: false,
contentType: false,
dataType: "json",
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});