Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add new value in collection laravel?

Tags:

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

like image 368
MisterPi Avatar asked Oct 21 '16 08:10

MisterPi


People also ask

How do you add value to a collection?

Java Collection add() methodThe add() method of Java Collection Interface inserts the specified element in this Collection. It returns a Boolean value 'true', if it succeeds to insert the element in the specified collection else it returns 'false'.

What is first () in Laravel?

For creating ::where statements, you will use get() and first() methods. The first() method will return only one record, while the get() method will return an array of records that you can loop over. Also, the find() method can be used with an array of primary keys, which will return a collection of matching records.

How do I combine two collections in Laravel?

Laravel collection merge() method merge any given array to first collection array. If the first collection is indexed array, the second collection will be added to the end of the new collection. The merge() method can accept either an array or a Collection instance.

How do you pluck in Laravel?

The Laravel pluck () as the name suggests, extracts certain values, as suggested. It literally plucks the information out from the given array and produces it as an output. However, it is most effective against objectives, but will work well against arrays too.


2 Answers

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

like image 166
Christian Giupponi Avatar answered Sep 19 '22 09:09

Christian Giupponi


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.

like image 45
suguna Avatar answered Sep 19 '22 09:09

suguna