Hi I am trying to insert multiple items into a laravel collection inside a php loop but only one is getting inserted (the last one), please help to insert all the values.
This array $some_array = array();
has values like 1,2,3,4
The loop is like
JavaScript
x
foreach ($some_array as $key => $value) {
$final_lists = collect([
(object) [
'customer_id' => $value,
],
]);
}
Output required
JavaScript
"final_lists": [
{
"customer_id": 4,
"name": "Name 1",
},
{
"customer_id": 2,
"name": "Name 2",
},
]
Advertisement
Answer
use collection class at the top of the page.as,
JavaScript
use IlluminateSupportCollection;
JavaScript
$collection = new Collection;
foreach([1,2,3,4] as $item) {
$collection->push((object)[
'customer_id' => $item,
'name' => 'demostring'.$item
]);
}
dd($collection->all());
use this snippet. Let me know the results.