Rediska's avatar

How to add one more property to each element of the collection?

Hi all! Can you please tell me how to add one more property to the collection? There are several tables, identical in columns - color, gender, material. To get all data I do this:

		$ages = Age::withTrashed()
            ->get();
        $colors = Color::withTrashed()
            ->get();
        $allParameters = $ages->concat($colors)->sortBy('created_at');

The problem is that in the general collection, I don't understand which element belongs to age, which one to color. How to add another property so that each element has a marker 'attribute' => 'age' or 'attribute' => 'color'

0 likes
2 replies
LaryAI's avatar
LaryAI
AI
Best Answer
Level 58

To add another property to each element of the collection, you can use the map method to iterate over each item in the collection and add the new property. Here's an example:

$ages = Age::withTrashed()->get();
$colors = Color::withTrashed()->get();

$allParameters = $ages->concat($colors)->sortBy('created_at')->map(function ($item) {
    if ($item instanceof Age) {
        $item->setAttribute('attribute', 'age');
    } elseif ($item instanceof Color) {
        $item->setAttribute('attribute', 'color');
    }
    return $item;
});

In this example, we're using the map method to iterate over each item in the collection and add the attribute property. We're checking the type of each item using the instanceof operator, and then setting the attribute property accordingly using the setAttribute method.

Now, each item in the $allParameters collection will have an attribute property with a value of either age or color, depending on which table it came from.

1 like

Please or to participate in this conversation.