Search code examples
phpmysqlarrayseloquentslim

How to get multiple values from a form and separate them with php


I don't know how this type of form done. I am not sure if this approach is correct.

I created a form which creates a delivery from a list of products. these products have an id (product_id) and quantity in the SQL table.

enter image description here

HTML code

<input type="hidden" name="quantity[]"  value="{{ product.product_id }}">
<input type="text" name="quantity[]" id="quantity" value="0" placeholder="Quantity" class="form-control form-control-sm">

I need to get quantity value for that particular product. I figured out until here but I don't know how to separate quantity array with PHP to be able to make it like a string so I can update the product quantities in the database.

Quantity output with below inputs:

enter image description here

$quantity = $request->getParam('quantity');
var_dump($quantity);
die();

enter image description here

I am using slim framework 3 and eloquent


Solution

  • You can use the product_id as the key for the quantity array which will give you a nicely formatted array to work with.

    <input type="text" name="quantity[{{ product.product_id }}]" id="quantity" value="0">
    

    This should give you:

    array (size=1)
      'quantity' => 
        array (size=2)
          'ABC' => string '0' (length=1)
          'DEF' => string '0' (length=1)
    

    With that, you can:

    foreach ($request->getParam('quantity') as $productId => $quantity) {
        // Create/update query.
    }