csrf-token expired before form submit - laravel

8
I have a form and I used {!! csrf_field()!!}
I have 2 select element one is for state and one is for the city
when state select change a ajax send and give new cities
if this ajax request doesn't execute we don't have a problem
but if ajax request send then form submit we give 419 page expired error
this is ajax code
$('#state').change(function () {
var state_id = $(this).val();
$.ajax({
type: 'get',
url: '/panel/selectCitiesByStateId/' + state_id,
data: {'nothing': 'nothing'},
timeout: 25000,
error: function () {
alert('sorry error');
},
success: function (res) {
res = JSON.parse(res);
var entires = Object.entries(res);
var htmlOptionElements = '';
for (var i = 0; i < entires.length; i++) {
var city = entires[i];
htmlOptionElements += '<option value="' + city[1] + '">' + city[0] + "</option>";
}
$('#city_id').html(htmlOptionElements);
}
})
});
this is the form top codes
<form action="{{route('admin.job.update',['job'=>$job->slug])}}"
method="post" enctype="multipart/form-data" id="jobForm">
{!! csrf_field() !!}
{!! method_field('patch') !!}
this is select codes
<div class="col-sm-6">
<label for="" class="control-label">state*</label>
<select name="state_id" id="state" class="form-control">
#foreach($states as $state)
<option value="{{$state->id}}"
#if($state->id==#$job->state_id)
selected
#endif
>{{$state->name}}</option>
#endforeach
</select>
</div>
<div class="col-sm-6">
<label for="" class="control-label">city*</label>
<select name="city_id" id="city_id" class="form-control">
#foreach($job->state->cities as $city)
<option value="{{$city->id}}"
#if(#$job->city->id==$city->id)
selected
#endif
>{{$city->name}}</option>
#endforeach
</select>
</div>

well,
one csrf token can be used once. and csrf token generate by a get request.
when you load the form by a get request, token generated and filled the form csrf field.
when the ajax fired on change of #state, you are sending a get request to the system. that means a new csrf token will be generated.
Thats why when you send the request (You already send get request by ajax), you got 419 error.
You can solve this problem by sending post request to ajax for #state, and disable csrf check for the route.
This May solve Your Problem.

Related

After form submit redirect without refresh using Ajax in laravel 8

I am developing multi Step Form Submit without refresh. collect the data from 1st step 2nd step collect some date, 3rd step collect some date & finally submit data in the database. Can you tell me how to fix this.
My blade template.
<form id="post-form" method="post" action="javascript:void(0)">
#csrf
<div>
<input class="form-input" type="text" id="ptitle" name="ptitle" required="required"
placeholder="What do you want to achieve?">
</div>
<button type="text" id="send_form" class="btn-continue">Continue</button>
</div>
</form>
Ajax Script
$(document).ready(function() {
$("#send_form").click(function(e){
e.preventDefault();
var _token = $("input[name='_token']").val();
var ptitle = $('#ptitle').val();
$.ajax({
url: "{{route('create.setp2') }}",
method:'POST',
data: {_token:_token,ptitle:ptitle},
success: function(data) {
alert('data.success');
}
});
});
Web.php router
Route::post('/setp2', [Abedoncontroller::class, 'funcsetp1'])->name('create.setp2');
Controller method
public function funcsetp1(Request $request) {
$postdata=$request->input('ptitle');
return response()->json('themes.abedon.pages.create-step-2');
}

refresh form with change in select option

So I want to refresh the update form with the change in the select option (which will be year).
This is my form:
<select class="form-control" id="year_select" name="year_select">
#foreach($pickyear as $key=>$unique)
<option value= "{!! $unique !!}"> {!! $unique !!} </option>
#endforeach
</select>
{!! Form::open(['url' => 'form', 'class' => 'form-horizontal']) !!}
//form is included here
{!! Form::close() !!}
So I want to reload or refresh the form with every change in select value or ajax call.
Ajax call:
$('select[name="year_select" ]).change(function(e) {
// e.preventDefault();
const year = $(this).val();
window.location.reload();
const url = `/form/${year}`;
$.ajax({
url,
type: 'PUT',
success: function(res) {
window.location.reload();
}
});
})
Edit: Refreshing / reloading whole page would do too.
Update: The imput parameter should be updatable and should change value according to the year from select option.
Use onchange="this.form.submit()" for page reload when Select Option change
on blade
<select name="year_select" onchange="this.form.submit()">
#foreach($pickyear as $key=>$unique)
<option value= "{!! $unique !!}"> {!! $unique !!} </option>
#endforeach
</select>
now url should be form_url?year_select=2022 and you can filter data from controller
On controller
$model = Model::query();
if (request('year_select')) {
$model->whereYear('your_year_column', request('year_select'));
}
// else
// {
// // if you need current year as default
// $model->whereYear('your_year_column', date('Y'));
// }
$data = $model->get();

How to fix AJAX modal form in Laravel 5.3

I've upgraded my app from Laravel 4.2 to Laravel 5.3. On an index page listing citations, I have an AJAX modal form to edit or view the login credentials for the citation. This was working fine in Laravel 4.2, but I cannot for the life of me get it to work in 5.3. After about 5 hours Googling and trying different things, I thought I would post it here so that someone way more experienced than me can point me in the right direction.
Here's the link on the index page:
<a style="cursor: pointer; " title= "Login Credentials" data-loopback="cit-pg-1" data-citationid="1079" class="getCitationdetails"><span class="glyphicon glyphicon-lock " title="Login Credentials"></span></a>
And here's the JavaScript:
<script type="text/javascript">
$(document).on('click','.getCitationdetails',function(){
var citationid = $(this).data('citationid');
var loopback = $(this).data('loopback');
$.ajax({
url : '/citation-password',
type:'post',
data : {citationid :citationid, loopback :loopback},
success:function(resp){
$('#AppendLoginDetails').html(resp);
$('#LoginCredentialsModal').modal('show');
$('.loadingDiv').hide();
},
error:function(){
alert('Error');
}
})
})
Here's my route:
Route::match(['get', 'post'], '/citation-password', 'CitationsController#citationpassword');
And here's the Controller method that generates the form on get and saves the data on post:
public function citationpassword()
{
if (Request::ajax()) {
$data = Request::all();
if (!$data['citationid']) {
return redirect('/citations')
->with('flash-danger', 'Missing citation id for Login credentials form!!');
}
// Save loopback variable if we have it in order to return user to the page where they came from; default return location is citations
$loopback = 'citations';
if (array_key_exists("loopback", $data)) {
$loopback = $data['loopback'];
}
$getcitationdetails = Citation::where('id', $data['citationid'])->select('id', 'site_id', 'username', 'password', 'login_email', 'login_notes')->first();
$getcitationdetails = json_decode(json_encode($getcitationdetails), true);
$getsitedetails = Site::where('id', $getcitationdetails['site_id'])->select(
'id',
'directory_username',
'directory_password',
'security_questions',
'email_account',
'email_account_password',
'email_account_name',
'google_user',
'google_pwd',
'name_of_google_account'
)->first();
$getsitedetails = json_decode(json_encode($getsitedetails), true);
$response ="";
$response .= '<form action="'.url('/citation-password').'" method="post">
<div class="modal-body">';
if (!empty($getsitedetails['directory_username'])) {
$response .= '<div class="form-group">
<label for="recipient-name" class="col-form-label">Default login credentials for this site:</label>
<p>Username: '.$getsitedetails['directory_username'].'
<br />Password: '.$getsitedetails['directory_password'].'
<br />Email account: '.$getsitedetails['email_account'].'
<br />Email password: '.$getsitedetails['email_account_password'].'
<br />Name on email account: '.$getsitedetails['email_account_name'].'
<br />Default security questions: '.$getsitedetails['security_questions'].'</p>
<p>Gmail account: '.$getsitedetails['google_user'].'
<br />Gmail password: '.$getsitedetails['google_pwd'].'
<br />Name on Gmail account: '.$getsitedetails['name_of_google_account'].'</p>
</div>';
}
$response .= '
<input type="hidden" name="_token" value="'.csrf_token() .'" />
<input type="hidden" name="citation_id" value="'.$data['citationid'].'" />
<input type="hidden" name="loopback" value="'.$loopback.'" />
<div class="form-group">
<label for="recipient-name" class="col-form-label">Username:</label>
<input type="text" class="form-control" name="username" value="'.$getcitationdetails['username'].'" autocomplete="off">
</div>
<div class="form-group">
<label for="message-text" class="col-form-label">Password:</label>
<input type="text" class="form-control" name="password" value="'.$getcitationdetails['password'].'" autocomplete="off">
</div>
<div class="form-group">
<label for="message-text" class="col-form-label">Login email used:</label>
<input type="text" class="form-control" name="login_email" value="'.$getcitationdetails['login_email'].'" autocomplete="off">
</div>
<div class="form-group">
<label for="message-text" class="col-form-label">Login notes:</label>
<textarea class="form-control" style="height:130px;" name="login_notes">'.$getcitationdetails['login_notes'].'</textarea>
</div>
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-success" id="success">Save</button>
<button type="button" class="btn btn-danger" data-dismiss="modal" aria-hidden="true">Cancel</button>
</div>
</form>';
return $response;
} else {
// The popup modal has posted back here; process the data
$data = Request::all();
// Handle & translate loopback; returning user to the page where they came from
$loopback = 'citations';
if ($data['loopback']) {
$loopback = $data['loopback'];
// Translate pages it came from
$trackLoopback = new trackLoopback();
$loopback = $trackLoopback->translate($loopback);
}
$updatecitation = Citation::find($data['citation_id']);
$updatecitation->username = $data['username'];
$updatecitation->password = $data['password'];
$updatecitation->save();
return redirect($loopback)
->with('flash-success', 'Login credentials have been updated successfully!');
}
}
In an effort to isolate the error, I even simplified the form in the controller like this:
public function citationpassword()
{
if (Request::ajax()) {
return '<p>This is the modal form!</p>';
} else {
// The popup modal has posted back here; process the data
$data = Request::all();
// Handle & translate loopback; returning user to the page where they came from
$loopback = 'citations';
if ($data['loopback']) {
$loopback = $data['loopback'];
// Translate pages it came from
$trackLoopback = new trackLoopback();
$loopback = $trackLoopback->translate($loopback);
}
$updatecitation = Citation::find($data['citation_id']);
$updatecitation->username = $data['username'];
$updatecitation->password = $data['password'];
$updatecitation->save();
return redirect($loopback)
->with('flash-success', 'Login credentials have been updated successfully!');
}
}
and also simplified the route to this:
Route::get('/citation-password', 'CitationsController#citationpassword');
but all I get when I click the link is a popup notice, "Error."
I'm not experienced with AJAX. How do I get the form to display in Laravel 5.3?
And/or, how can I change the JavaScript function so that it shows the actual error instead of the "Error" notice? (I tried a number of methods I found on StackOverflow to display errors but all of them resulted in NO error notice; just a blank page. And, I've not been successful at getting my Firefox debugger to show the errors either.)
Thanks!
The correct way to debug the JavaScript is to post the errors this way:
<script type="text/javascript">
$(document).on('click','.getCitationdetails',function(){
var citationid = $(this).data('citationid');
var loopback = $(this).data('loopback');
$.ajax({
url : '/citation-password',
type:'post',
data : {citationid :citationid, loopback :loopback},
success:function(resp){
$('#AppendLoginDetails').html(resp);
$('#LoginCredentialsModal').modal('show');
$('.loadingDiv').hide();
},
error: function(xhr, ajaxOptions, thrownError) {
alert(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText);
}
})
})
Once you do so, you will see that the error has to do with missing CsrfToken for the form. [The actual error message is from the Laravel framework: Illuminate\Session\TokenMismatchException: in file /home/reviewsites/moxy53/vendor/laravel/framework/src/Illuminate/Foundation/Http/Middleware/VerifyCsrfToken.php on line 6] Since both the get and post verbs use the same route, Laravel is requiring the CsrfToken before the form with the Csrf field gets generated.
It is possible (but NOT recommended!) to exclude this route from CSRF protection by editing App\Http\Middleware\VerifyCsrfToken.php with the following exception:
/**
* The URIs that should be excluded from CSRF verification.
*
* #var array
*/
protected $except = [
'/citation-password',
];
However, a much better approach is to add the token. It is correct that since you are using a post method to send the data values to the controller, you cannot use the controller to generate the token field in the form. Hence, the solution is to take the html out of the controller and put it in the blade. These lines:
$response .= '<form action="'.url('/citation-password').'" method="post">
<div class="modal-body">';
...
</div>
</form>';
should not be in the $response generated by the controller, but should instead be in the modal div in the blade itself. THEN, you can add the CSRF field in the blade thus:
<form action="{{url('/citation-password')}}" method="post">
{{ csrf_field() }}
<div class="modal-body" id="AppendLoginDetails">
</div>
</form>

Laravel Select2 old input after validation

I'm using Select2 in my webapplication. I load my Select2 boxes with Ajax. When validation fails, all the inputs are filled as before except the Select2 box. How can I restore the old value after the form validation fails? My bet was using Request::old('x'), but this inserts the value (in my case an user ID) instead of the selected text. So for example the text John would become 27 in the selectbox. How can I get the text back?
<select id="customer" name="customer" class="searchselect searchselectstyle">
</select>
The js:
token = '{{csrf_token()}}';
$(".searchselect").select2({
ajax: {
dataType: "json",
type: "POST",
data: function (params) {
return {
term: params.term,
'_token': token,
'data' : function(){
var result = [];
var i = 1;
$('.searchselect').each(function(){
result[i] = $(this).val();
i++;
});
return result;
}
};
},
url: function() {
var type = $(this).attr('id');
return '/get' + type;
},
cache: false,
processResults: function (data) {
return {
results: data
};
}
}
});
Edit
The only (dirty) solution I found so far is the following:
<select id="customer" name="customer" class="searchselect searchselectstyle">
#if(Request::old('customer') != NULL)
<option value="{{Request::old('customer')}}">{{$customers->where('id', intval(Request::old('customer')))->first()->name}}</option>
#endif
</select>
$customers is a list of all customers, so this means that for each Select2 box I need to query a big list of items in order to make it work. This will be pretty inefficient if we're talking about thousands of rows per Select2 box.
I guess there must be a better solution. Who can help me?
Normally to programmatically set the value of a select2, you would expect to use the .val() method followed by a .trigger('change') call as per their documentation (and other queries like this on SO). However, select2 themselves have something in their documentation about preselecting options for remotely sourced data.
Essentially their suggestion boils down to (after initalizing your AJAX-driven <select>):
make another AJAX call to a new API endpoint using the pre-selected ID
dynamically create a new option and append to the underlying <select> from a promise function (.then()) after the AJAX call is finished
could also use some of the regular jQuery callback chaining functions for this
trigger a change event
trigger a select2:select event (and pass along the whole data object)
Assuming you're already flashing the old data to the session, Laravel provides handy access to the previously requested input in a variety of ways, notably these three:
static access via the Request class e.g. Request::old('customer') as in the OP
the global old() helper e.g. old('customer'), which returns null if no old input for the given field exists, and can have a default as a second parameter
using the old() method on the Request instance from the controller e.g. $request->old('customer')
The global helper method is more commonly suggested for use inside Blade templates as in some of the other answers here, and is useful when you don't need to manipulate the value and can just plug it straight back in, which you would with things like text inputs.
The last method probably provides you with the answer you're looking for - instead of querying the entire collection from inside of the view, you're able to either manipulate the collection from the controller (similar to the OP, but should be nicer since it's not parsing it in the view) or make another query from the controller based on the old ID and fetch the data you want without having to trawl the collection (less overhead):
$old_customer = Customer::find($request->old('customer'));
Either way, you'd have the specific data available at your fingertips (as a view variable) before the blade template processes anything.
However you choose to inject the data, it would still follow the pattern suggested by select2:
get the pre-selected data
create an option for it
trigger the appropriate events
The only difference being you don't need to fetch the data from another API endpoint (unless you want/need to for other programmatic reasons).
I end up using similar flow like your. But my blade template is using htmlcollection package.
Controller:-
Let's say you are in create() method. When validation failed, it will redirect back to the create page. From this page, you can repopulate the list.
$customer_list = [];
if(old('customer') != NULL){
$customer_list = [old('customer') => $customers->where('id', old('customer'))->first()->name];
}
Blade View:
{{ Form::select('customer', $customer_list, null, ['class' => 'searchselect searchselectstyle', 'id' => 'customer']) }}
I did it with an input hidden for the text and it works well:
This form is showed in a Popup and ajax (using Jquery-UJS)
Form:
<form action="{{ route('store_item', $order) }}" method="POST" data-remote="true">
{{ csrf_field() }}
<div class="form-group{{ $errors->has('item_id') ? ' has-error' : '' }}">
<label class="control-label col-sm-2" for="item_id">Item: </label>
<div class="col-sm-10">
<select name="item_id" class="form-control" id="item_id">
#if(old('item_id') != null)
<option value="{{ old('item_id') }}" selected="selected">
{{ old('item_title') }}
</option>
#endif
</select>
</div>
{!! $errors->first('item_id', '<p class="text-center text-danger"<strong>:message</strong></p>') !!}
</div>
<input type="hidden" id="item_title" name ="item_title" value="{{ old('item_title') }}" />
<div class="form-group{{ $errors->has('quantity') ? ' has-error' : '' }}">
<label class="control-label col-sm-2" for="quantity">Cantidad: </label>
<div class="col-sm-10">
<input name="quantity" type="number" class="form-control" id="quantity" value="{{ old('quantity') }}"/>
</div>
{!! $errors->first('quantity', '<p class="text-center text-danger"><strong>:message</strong></p>') !!}
</div>
<button type="button" class="btn btn-default" data-dismiss="modal">Cancelar</button>
<button type="submit" class="btn btn-primary" data-disable-with="Guardando...">Guardar</button>
</form>
JAVASCRIPT:
<script type="text/javascript">
$(document).ready(function(){
$('#item_id').select2({
placeholder: 'Elige un item',
ajax: {
url: '{{ route('select_item_data') }}',
dataType: 'json',
delay: 250,
processResults: function (data) {
return {
results: $.map(data, function (item) {
return {
text: item.title,
id: item.id
}
})
};
},
cache: true
}
});
$('#item_id').on('change', function(e){
var title = $(this).select2('data')[0].text;
$('#item_title').val(title);
});
});
</script>
VALIDATION IN STORE METHOD (CONTROLLER):
$validator = Validator::make($request->all(), [
'item_id' => 'required',
'quantity' => 'required'
]);
if ($validator->fails()) {
return redirect()
->route('create_item', $order)
->withInput($request->all())
->withErrors($validator);
}
It's very important to send 'withInput' and 'withErrors' in the redirection, because we are working with a popup and ajax that is created again and doesn't keep the old values.
Maybe you can try (once the ajax call has ended) :
var oldCustomer = $('#customer > option[value={{ Request::old('customer') }}]');
if (oldCustomer.length > 0) {
oldCustomer.attr('selected', 'selected');
}
Same problem; I'm using a similar solution: If the old $id is set, I get the name and I use it as a variable for the view; Note that I also forward the id because I also used this method to pre-fill the form (coming from another place), but in this case, the name only should have been used, and for the id {{ old('author_id') }} can be used in the view:
In the controller:
elseif (($request->old('author_id') !== null) && ($request->old('author_id') != '')) {
$my_author_id = $request->old('author_id');
$my_name = Author::find($my_author_id)->name;
return view('admin/url_author.create', compact('my_name', 'my_author_id'));
}
And in the view (more precisely, in a partial used for creation & edition):
#if (isset($record)) // for use in edit case with laravelcollective)
<select class="form-control js-data-author-ajax" id="author_id" name="author_id">
<option value="{{ $record->author_id }}">{{ $record->author->name }}</option>
</select>
#else
#if (isset($my_name)) // old input after validation + pre-filling cases
<select class="form-control js-data-author-ajax" id="author_id" name="author_id">
<option value="{{ $my_author_id }}">{{ $my_name }}</option>
</select>
#else // for create cases
<select class="form-control js-data-auteur-ajax" id="auteur_id" name="auteur_id">
<option></option>
</select>
#endif
#endif
Your code is bit confusing. I don't understand why you are using a POST request to get data using ajax to fill a select2 box.
Assuming the data returned using ajax call is in the below format.
[
{
"id": "Some id",
"text": "Some text"
},
{
"id": "ID 2",
"text": "Text 2"
},
]
Now what you can do is pass in an extra parameter to your ajax call as below
url: function() {
var type = $(this).attr('id');
#if(old('customer'))
return '/get' + type + '?customer='+ {{ old('customer') }};
#else
return '/get' + type;
#endif
}
Now in your controller while returning data you can throw an extra attribute selected:true for an ID matching that particular ID.
if( Request::has('customer') && Request::input('customer') == $id )
{
[
"id" => $id,
"text" => $text,
"selected" => "true"
]
}
else
{
[
"id" => $id,
"text" => $text,
]
}
If I understood you right I can recommend you to have for each your select2 box hidden input <input type="hidden" name="customer_name" value="{{old('customer_name', '')}}"> where after change event for select2 you can insert selected name (etc. John). So if validation is fails you have:
<select id="customer" name="customer" class="searchselect searchselectstyle">
#if(!is_null(old('customer')))
<option value="{{old('customer')}}">{{old('customer_name')}}
</option>
#endif
</select>
I think your own solution is pretty much correct. You say the list of $customers will get pretty big.
$customers->where('id', intval(Request::old('customer')))->first()
Do you need to have the list stored in a variable $customers? You could just search the id you want
App\Customer::where('id', intval(Request::old('customer')))->first()
Searching by id should not be inefficient. Otherwise you could send the name with the form and store it in the old request. Shown below with some (dirty) javascript.
$("#form").submit( function() {
var sel = document.getElementById("customer");
var text= sel.options[sel.selectedIndex].text;
$('<input />').attr('type', 'hidden')
.attr('name', "selected_customer_name")
.attr('value', text)
.appendTo('#form');
return true;
});
Then like yrv 16s answer:
<option value="{{old('customer')}}">{{old('selected_customer_name')}}
You could do something like this:
First in controller pass tags to view using pluck helper like below:
public function create()
{
$tags= Customer::pluck('name','name');
return view('view',compact('tags'));
}
Then in your form try this:
{!! Form::select('tag_list[]',$tags,old('tag_list'),'multiple','id'=>'tag_list']) !!}
Don't forget to call the select2 function.
$('#tag_list').select2();
And finally in controller:
public function store(ArticleRequest $request)
{
$model = new Model;
$tags=$request->input('tag_list');
$model->tag($tags);
}
Notice tag function is not a helper in Laravel, You implement it! The function takes names and attaches them to the instance of some thing.
Good Luck.

Laravel 5 missmatch token in sending email

i'm using ajax to send email so i my problem is if i dont have
{!! csrf_field() !!}
in view i will get the token missmatch error.If i add input hidden token in view i will get this error
Swift_RfcComplianceException in MailboxHeader.php line 348: Address in
mailbox given [] does not comply with RFC 2822, 3.6.2.
How can i fix it.Thanks for help.
here it's view
<form action="{{ url('/findpass')}}" method="POST" id="forgotpassForm">
{!! csrf_field() !!}
<div class="form-group">
<input class="form-control input-lg" placeholder="E-mail" name="emailForgot" type="email" id="emailForgot" required>
</div>
<input type="submit" class="btn btn-lg btn-primary btn-block" id="forgotpassBtn" value="Send email">
</form>
Ajax
$(document).ready(function() {
$('#forgotpassBtn').click(function() {
event.preventDefault();
var email=$("#emailForgot").val();
var _token = $("input[name='_token']").val();
$.ajax({
url: '/findpass',
type: 'POST',
data:{
email:email,
_token : _token
},
success:function(data) {
alert(data.mess);
$("#forgotpass")[0].reset();
},
error:function() {
alert("Error");
}
});
});
});
Controller
public function resetPass()
{
$emailForgot=Input::get('emailForgot');
$user= User::where('email', '=' , $emailForgot)->first();
$data=['username'=>$user -> username,'email'=>$user -> email,'token'=>$user -> remember_token];
Mail::send('ui.mail.reset',$data, function ($m) use ($user) {
$m->from('ngohungphuc95#gmail.com', 'Reset password');
$m->to($user->email, $user->full_name)->subject('Email reset password');
});
return response()->json(array('mess'=>'Mail send'));
}
Add the csrf without blade and add an id by yourself. Get the value of csrf value by id using jquery. Here is how you can do this.
Change {!! csrf_field() !!} to:
<input type="hidden" name="_token" value="{{ csrf_token() }}" id="token"/>
And Change this line of ajax code:
var _token = $("input[name='_token']").val();
To:
var _token = $('#token').val();
May be this is not the best way. But I solved my problem with this procedure.
You could also add a global csrf token to all ajax calls like this
$(document).ready(function(){
$.ajaxSetup({
headers: { 'X-CSRF-Token': $('meta[name="csrf-token"]').attr('content') },
});
});
Then just override the tokensMatch() method of the VerifyCsrfToken token to also look for the ajax header
protected function tokensMatch($request)
{
// If request is an ajax request, then check to see if token matches token provider in
// the header. This way, we can use CSRF protection in ajax requests also.
$token = $request->ajax() ? $request->header('X-CSRF-Token') : $request->input('_token');
return $request->session()->token() == $token;
}
After this all your ajax calls will automatically pass csrf checks and be secure.
Swift_RfcComplianceException in MailboxHeader.php line 348: Address in mailbox given [] does not comply with RFC 2822, 3.6.2.
The above error is because you haven't configured a from address in config/mail.php. It is set to null by default, but should be a valid email address:
'from' => ['address' => 'user#example.com', 'name' => null],

Resources