Skip to content
Advertisement

Insert multiple items in Laravel Collection inside a php loop

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

foreach ($some_array as $key => $value) {

                $final_lists = collect([
                    (object) [
                        'customer_id' => $value,
                    ],
                ]);
            }

Output required

"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,

use IlluminateSupportCollection;
$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.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement