Reputation: 245
I working on laravel 5.1. I was stuck on figuring how to store my 2 arrays input into the same row on DB. I only know how to store for one array.
$amount[] = $request->amount;
$receipt[] = $request->receipt;
foreach ($amount as $key => $value) {
$reimbursement_item = ReimbursementItem::create([
'user_id' => $user->id,
'amount' => $value,
]);
}
DB structure and aspect result:
id user_id amount receipt
-- ------- ------ --------------
1 32 40.00 /images/r1.jpg
2 24 60.00 /images/r2.jpg
Upvotes: 0
Views: 920
Reputation: 64466
Its better if you could update your request object structure like there should be one array and each index of array will have values for amount and receipt not individual arrays of amount and receipt
$data[] = $request->data;
foreach ($data as $key => $value) {
$reimbursement_item = ReimbursementItem::create([
'user_id' => $user->id,
'amount' => $value['amount'],
'receipt' => $value['receipt']
]);
}
Another approach would be , If length of both arrays $amount
and $receipt
is same each time and the values are in correct order you can also update your data in single loop like
foreach ($amount as $key => $value) {
$reimbursement_item = ReimbursementItem::create([
'user_id' => $user->id,
'amount' => $value,
'receipt' => (isset($receipt[$key]))? $receipt[$key]: null
]);
}
Upvotes: 2