So I have this post request data
array:6 [▼
"_token" => "oZ5OjnWU4svOPPFXMrzkDIBau92yIxd7l1Onn1EN"
"orderId" => "2"
"product_id" => array:3 [▼
0 => "111"
1 => "222"
2 => "333"
]
"product_price" => array:3 [▼
0 => "150.00"
1 => "1800.00"
2 => "800.50"
]
"discount" => "10.00"
"status" => "SUCCESS"
]
and I'm trying to save it to my table using this code.
public function upsellStore( Request $request ) {
$input = $request->all();
foreach($input['product_id'] as $id ) {
$order = new OrderProduct;
$order->orderid = $input['orderId'];
$order->discount = $input['discount'];
$order->status = $input['status'];
$order->product_id = $id;
$order->product_price = $input['product_price'];
$order->save();
}
return $order;
}
however I'm not sure how to save it. product_id and product_price should be aligned so the output of this save should be something like this
<table>
<tbody>
<tr>
<th>ID</th>
<th>Product ID</th>
<th>Price</th>
<th>Discount</th>
<th>Status</th>
</tr>
</tbody>
<tbody>
<tr>
<td>1</td>
<td>111</td>
<td>150.00</td>
<td>10.00</td>
<td>SUCCESS</td>
</tr>
<tr>
<td>1</td>
<td>222</td>
<td>1800.00</td>
<td>10.00</td>
<td>SUCCESS</td>
</tr>
<!-- and so on... -->
</tbody>
</table>
CodePudding user response:
Pablo. Best regards. Your product_price is an array, therefore you can't do:
$order->product_price = $input['product_price'];
I would make a different approach in the view that contains the form, in order to be sure that the array of product_id matches the size/sequence of product_price (better readability/maintenance).
But to solve the problem the way you presented, you need to get the key of product_id, and use that key to retrieve the price, like this:
foreach($input['product_id'] as $key => $id ) { $order = new OrderProduct; $order->orderid = $input['orderId']; $order->discount = $input['discount']; $order->status = $input['status']; $order->product_id = $id; $order->product_price = $input['product_price'][$key]; $order->save(); }
