Jamie Jamie - 1 month ago 18
PHP Question

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

]
]

Answer

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;
}