Using x-editable to create an editable form that sends requests via ajax. The form looks like this:
<a href="#" class="editable editable-click" id="mileage"
data-name="mileage"
data-type="number"
data-pk="{{ $car->id }}"
data-original-title="Enter mileage">
{{ $car->mileage }}
</a>
Then goes the JS:
$('#mileage').editable({
url: '{{ route('changeMileage', $car->id) }}',
type: 'number',
pk: {{ $car->id }},
name: 'mileage',
title: 'Enter mileage in km',
validate:function(value){
if ($.trim(value) === '') {
return "Field is required";
}
}
})
In my controller:
$car = Car::where('id', $id)->first();
$this->validate($request, [
'value' => 'number|min:' . $car->mileage . '|max:999999',
]);
$car->update([$car->mileage => $request->value]);
The controller code is a bit messed because I tried different versions of it. Just because I need to validate (entered mileage can not be less then existing one).
But the problem is that once I send the request, I got the Integrity constraint violation: 1048
error, that says that the mileage
field is empty. Running dd($request->value)
gives me null
, but monitoring the request from the browser, it goes as intended: name=mileage&value=325000&pk=1
.
Somehow the controller is missing the value
value. Any solutions, please?
P.S. I intentionally did not check for pk
value, because I have only one field to edit on the current page that already has the id
information.
P.P.S. I tried every method I could imagine - dd($request->all())
still returns an empty array - [].
Well, even if x-editable is abandoned, it works. With help from other developers, I came up with that solution.
In my JavaScript code, added the following line after every other options:
ajaxOptions: {
dataType: 'json'
},
Before that, in the same JS file, added a line to set up the ajax headers:
$.ajaxSetup({
headers: {
'Content-Type': 'application/json',
"X-CSRF-Token": "{{ csrf_token() }}",
'X-Requested-With': 'XMLHttpRequest',
'Content-type': 'application/x-www-form-urlencoded; charset=UTF-8'
},
});
In Controller added a check to see if the request is sent via ajax:
if($request->ajax()) {
$car->update(['mileage' => $request->input('value')]);
return response()->json(['success' => true]);
}
And the request now goes as follows: name=mileage&value=325002&pk=1
After that, it works like a charm!