Home > Net >  Insert multiple items in Laravel Collection inside a php loop
Insert multiple items in Laravel Collection inside a php loop

Time:09-28

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

CodePudding user response:

use collection class at the top of the page.as,

use Illuminate\Support\Collection;
$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.

CodePudding user response:

If you require a list of multiple collections, you can append a new collection to an array like:

$a = [1,2,3,4,5]; // Your Array
$requiredList = [];
foreach($a as $key => $value){
    $requiredList[] = (object)[
        'customer_id' => $value,
        'name' => 'Customer Name: ' . $value
    ];
}
dd($requiredList);

It will provide the desired list like:

^ array:5 [▼
  0 => {#3971 ▼
     "customer_id": 1
     "name": "Name1"
  }
  1 => {#3207 ▼
     "customer_id": 2
     "name": "Name2"
  }
  2 => {#3977 ▼
     "customer_id": 3
     "name": "Name3"
  }
  3 => {#3961 ▼
     "customer_id": 4
     "name": "Name4"
  }
  4 => {#3956 ▼
     "customer_id": 5
     "name": "Name5"
  }
]
  • Related