0

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
5
  • You want to store two rows? Commented May 31, 2018 at 6:39
  • @AliN11 one row Commented May 31, 2018 at 6:42
  • Post current table data with expected data structure. Commented May 31, 2018 at 6:45
  • It's strange. How is it possible to store two different arrays in one row? Commented May 31, 2018 at 6:46
  • merge the two array and then store it Commented May 31, 2018 at 6:58

1 Answer 1

2

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
  ]);
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.