简体   繁体   中英

How to save multiple form field into database using laravel 5.4

I have multiple form field generated by jquery but only save last one record to database

<tr>
    <td><input class="form-control" id="quantity[]" name="quantity[]" placeholder="Quantity" type="text"></td>
    <td><input class="form-control" id="price[]" name="price[]" placeholder="Enter Pice" type="text"></td>
</tr>

The jquery that generate additional form fields is here

 $('#priceTable').append(
     "<tr> <td><input class='form-control' id='quantity[1]' name=\"quantity[]\" placeholder='Quantity' type='text'></td><td><input class='form-control' name=\"price[]\"  id='price[1]' +' placeholder='Enter Pice' type='text'></td> </tr>"\
 );

The result from on the php page is show below

array([quantity] => Array ( [0] => 45 [1] => 60 ) [price] => Array ( [0] => 45000 [1] => 60000 )

The loop that suppose to post it to database but post only one to database

 for ($i=0; $i <= $noQuantity; $i++ )
        {
           if(!empty($price)){
               $data = [
                   'price' => $priceRe[$i],
                   'quantity' => $quantity[$i]
               ];
               $price->create($data);
               return redirect('/admin123/category');
           }

         }

It's only creating one because you're redirecting inside the loop, so it creates the first one, and then sends the user to the other page. Try moving it out:

for ($i=0; $i <= $noQuantity; $i++ )
{
    if(!empty($price)){
        $data = [
            'price' => $priceRe[$i],
            'quantity' => $quantity[$i]
        ];
        $price->create($data);
    }
}
return redirect('/admin123/category');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM