Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

bach's avatar
Level 3

Is there any way to add attribute to objects in collection?

Hello,

I finally understood Collections.

However, I am looking to add an attribute (pulled from an external database) to each object of the collection. I will then send the collection to the View.

Any way to do so?

Thank you!

0 likes
7 replies
bach's avatar
Level 3

A bit more reading and I figured it.

Just in case someone has the same question, read about Collection's put().

thomaskim's avatar

@bach Hmmm... the collection's put() method should add an item to the collection, not an attribute to each model of the collection. Are you sure that's what you were looking for?

2 likes
bach's avatar
Level 3

@thomaskim hey thanks for the reply. You are totally right, I only really figured that out way after posting my reply.

put() inserts an item in the collection.

I am running foreach() on a collection, which gets me a single item every time, and within theforeach(), I insert an item to the array like so $clinic['total_yesterday'] = $total_yesterday; which adds an attribute to each single array.

In the foreach function, I use the & to save the modifications on the the actual collection. Here is my code:

public function all()
    {
      $clinics = Clinic::all()->sortBy('full_name');
    
    foreach($clinics as &$clinic) {

[...]

    $clinic['total_yesterday'] = $total_yesterday;
    }
}

It works fine.

Am I doing everything right? Thanks for the reply.

michaelaberra's avatar

You can use map.

$user = User::all();

$user->map(function ($u) {

$u['AttributeName'] = 'Attribute Value';

return $u

});

Then object user should have Attribute Name added to it

1 like
CamKem's avatar

@michaelaberra Please do not add replies to old threads, if you need to ask a question or want to give suggestions create a new thread.

1 like

Please or to participate in this conversation.