I'm trying to create a shopping cart and I want to POST multiples fields with same name and process them
<?php foreach($datacart as $datacart) { ?>
<form method="post" action="/update-cart">
<input type="hidden" name="rowid" value="{{$datacart->rowid}}">
<input type="text" name="quantity" value="{{$datacart->quantity}}">
<?php }>
<input type="submit" value="update">
</form>
public function update_cart(request $request){
$rowId = $request->rowid;
$quantity = $request->quantity;
Cart::update($rowId, $quantity);
}
First displaying all products using a foreach. Then each item has a hidden rowid and a quantity.
Below code is showing my controller. But with this code, it only updates one item (lastone). But I want to update each product's quantity separately
Forgot to mention, I use https://github.com/Crinsane/LaravelShoppingcart as my cart plugin
First of lets improve your blade file, you can use blade syntax instead of PHP, so here:
<form method="post" action="/update-cart">
@csrf
@foreach($datacart as $datacart)
<input type="hidden" name="rowid[]" value="{{$datacart->rowid}}">
<input type="text" name="quantity[]" value="{{$datacart->quantity}}">
@endforeach
<input type="submit" value="update">
</form>
so notice the name attributes of the input elements now are accepting multiple values as an array. Then to process it in your controller you can do the following:
public function update_cart(Request $request) {
foreach ( $request->rowid as $index => $id ) {
Cart::find($id)->update(['quantity' => $request->quantity[$index]]);
}
}
-- EDIT
Just tested calling update on the model as static method won't work.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With