27

I have the following loop where I try to add a new value:

 foreach ($pro->sig()->get() as $key => $sig) {
            $sig->val = 2;
        }

When I print the output of $pro->sig() I don't have the new value $sig->val

Christian Giupponi
  • 7,408
  • 11
  • 68
  • 113
MisterPi
  • 1,471
  • 5
  • 17
  • 23

3 Answers3

45

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

Christian Giupponi
  • 7,408
  • 11
  • 68
  • 113
13

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": "test@test.com",
    "test": "test"
  }

Please try like this.

suguna
  • 781
  • 5
  • 14
4
$users = User::find(1);

$user->objectName = " Value ";

that works fine if you just need to push another object in the collection by eloquent.

Abilogos
  • 4,777
  • 2
  • 19
  • 39
Waqas Mustafa
  • 192
  • 1
  • 7