I was stuck on figuring how to store my arrays of data into a single one so I can insert it on the table using eloquent. I am using a javascript to add dynamic rows. Here's the js:
$(function(){
var rowCount = document.getElementById('tblContacts').rows.length - 1 ;
var rowArrayId = rowCount ;
function addRow(){
$("#tblContacts tbody").append(
"<tr>"+
"<td><input type='text' name='product[" + rowArrayId + "][name]' class='form-control'/></td>"+
"<td><textarea name='product[" + rowArrayId + "][description]' class='form-control' rows='1'></textarea></td>"+
"<td><input type='text' name='product[" + rowArrayId + "][quantity]' class='form-control'/></td>"+
"<td><input type='text' name='product[" + rowArrayId + "][price]' class='form-control'/></td>"+
"<td><button class='btnRemoveRow btn btn-danger'>Remove</button></td>"+
"</tr>");
$(".btnRemoveRow").bind("click", removeRow);
rowArrayId = rowArrayId + 1; };
function removeRow(){
var par = $(this).parent().parent(); //tr
par.remove();
};
});
and here's my html file
<tr>
<td><input type='text' name='product[0][name]' class="form-control"/></td>
<td><textarea name='product[0][description]' class="form-control" rows="1"></textarea></td>
<td><input type='text' name='product[0][quantity]' class="form-control"/></td>
<td><input type='text' name='product[0][price]' class="form-control"/></td>
<td><button class="btnRemoveRow btn btn-danger">Remove</button></td>
</tr>
$(".btnRemoveRow").bind("click", removeRow);
$("#btnAddRow").bind("click", addRow);
and in my controller when I tried to use
$input = Input::get('product');
dd($input);
I got these result:
array (size=3)
0 =>
array (size=4)
'name' => string 'first product' (length=13)
'description' => string 'first product description' (length=25)
'quantity' => string '10' (length=2)
'price' => string '15' (length=2)
1 =>
array (size=4)
'name' => string '2nd product ' (length=12)
'description' => string '2nd product description' (length=23)
'quantity' => string '20' (length=2)
'price' => string '20' (length=2)
2 =>
array (size=4)
'name' => string '3rd product ' (length=12)
'description' => string '3rd product description' (length=23)
'quantity' => string '25' (length=2)
'price' => string '30' (length=2)
I learned it from here: Generating New Array from Laravel 4 Input
my question is how can i put these arrays into a single array to come up like these code
$insert = array();
foreach($tab as $key => $value)
{
$insert[] = array(
'id_reservation' => $reservation_id,
'produit_id' => $key,
'quantite' => $value
);
}
DB::table('products')->insert($insert);
I also get the above code from here: [SOLVED] fluent query builder multiple insert with a foreach