I'm working on a shopping cart with Laravel.
I have :
Routes :
Route::post('/panier/ajouter', 'CartController@store')->name('cart.store');
Route::patch('/panier/{product}', 'CartController@update')->name('cart.update');
View :
<table class="table" id="table-shoppingcart">
<thead>
<tr>
<th class="text-center" id="item-title-shoppingcart"></th>
<th class="text-center" id="size-title-shoppingcart">Taille</th>
<th class="text-center" id="quantity-title-shoppingcart">Quantité</th>
<th class="text-center" id="price-title-shoppingcart">Prix</th>
{{-- <th class="text-center" id="delete-title-shoppingcart"></th> --}}
</tr>
</thead>
<tbody>
@foreach (Cart::content() as $product)
<tr>
<th><img class="text-center item-content-shoppingcart" src="{{ $product->model->image }}"></th>
<td class="text-center td-table-shoppingcart size-content-shoppingcart">S</td>
<td class="td-table-shoppingcart quantity-content-shoppingcart">
<select name="quantity" class="custom-select text-center quantity" id="quantity" data-id="{{ $product->rowId }}">
@for ($i = 0; $i < 5 + 1 ; $i++)
<option id="quantity-option" {{ $product->qty == $i ? 'selected' : '' }}>{{ $i }}</option>
@endfor
</select>
</td>
<td class="text-center td-table-shoppingcart price-content-shoppingcart">{{ getPrice($product->subtotal()) }}</td>
</tr>
@endforeach
</tbody>
</table>
Ajax request :
$("#quantity").change(function(){
const classname = document.querySelectorAll('#quantity')
Array.from(classname).forEach(function(element) {
console.log(element);
let id = element.getAttribute('data-id')
axios.patch(`/panier/${id}`, {
quantity: this.value
})
.then(function (response) {
// console.log(response);
console.log("refresh");
$("#table-shoppingcart").load(location.href + " #table-shoppingcart");
})
.catch(function (error) {
console.log("erreur");
// console.log(error);
});
})
});
I need to get the quantity in my controller so i try :
public function update(Request $request)
{
$data = $request->json()->all();
Log::info($data);
return response()->json(['success' => 'Cart Quantity Has Been Updated']);
}
But when i try to get a $data value, my array is empty like this in my log :
[2020-02-22 10:49:46] local.INFO: array ()
I tryed to change :
$data = $request->json()->all();
To
$data = $request->all();
But same problem.
Do you have any idea ?
Thanks !
axios.patchis now working properly refer this stackoverflow.com/questions/51170564/…thisis referring local scope in JS . since you are using Jquery I don't see the point of usingthis. you need to inject the event to you change function and from there you can get the value. let me know if need you need post it answer