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
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'.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With