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
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
]);
}
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.