Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

POST multiple fields with same name in Laravel

Tags:

php

laravel

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

like image 382
Kelum Isuranga Avatar asked Oct 25 '25 14:10

Kelum Isuranga


1 Answers

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.

like image 128
nakov Avatar answered Oct 27 '25 02:10

nakov