How to add new value in collection laravel?

If you have a collection you can use push or put method.

Example with put:

$collection = collect(['product_id' => 1, 'name' => 'Desk']);

$collection->put('test', 'test');

$collection->all();

The output will be:

['product_id' => 1, 'name' => 'Desk', 'test' => 'test']

Example with push:

$collection = collect([1, 2, 3, 4]);

$collection->push(5);

$collection->all();

Output:

[1, 2, 3, 4, 5]

Reference: https://laravel.com/docs/5.3/collections#method-push

update Reference for 5.8: https://laravel.com/docs/5.8/collections#method-push


In my example, I tried like the below

foreach ($user->emails as $key => $email) {
   $email->test = "test";
}
return $user->emails;

It outputs like,

  {
    "id": 76,
    "user_id": 5,
    "additional_email": "[email protected]",
    "test": "test"
  }

Please try like this.