Jamie
Jamie

Reputation: 10906

Laravel save multiple records

I've got an array within arrays and would like to add something to it.

$options = $request->options;
foreach ($options as $option) {
    $option['poll_id'] = $this->id;
}

dd($options);

But for some reason it does not add to the array.

So I receive this:

array:1 [
  0 => array:1 [
    "name" => "testtest"
  ]
]

But I would expect this:

array:1 [
  0 => array:1 [
    "name"    => "testtest",
    "poll_id" => 1 

  ]
]

Upvotes: 1

Views: 672

Answers (2)

Saumya Rastogi
Saumya Rastogi

Reputation: 13709

You should do it using the $key attribute on arrays

// Suppose your $request->options is like:
$options = [
  0 => [
    "name" => "testtest"
  ]
];

foreach ($options as $key => $option) {
    $options[$key]['poll_id'] = 3; // Changing variable - $options here.
}

and it should work!

// $options would be like:

array:1 [▼
  0 => array:2 [▼
    "name" => "testtest"
    "poll_id" => 3
  ]
]

Upvotes: 1

Alexey Mezenin
Alexey Mezenin

Reputation: 163978

You're not changing $options so foreach is destroying $option with each iteration. Try something like this instead:

$options = [];
foreach ($request->options as $key => $value) {
    $options[$key]['poll_id'] = $this->id;
}

Upvotes: 1

Related Questions