Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Merging multiple objects which uses same id

I'm trying to merge multiple objects (like Receipts, Reports, etc) with Collection->merge().

This is the code I used:

$receipts = Receipt::all();
$reports  = Report::all();

$collection = $receipts->merge($reports);

This is the result:

enter image description here

The above screenshot shows two elements, but the third element is missing because it has the same id (id: "1") as the first one. What I'm trying to achieve is to display all three of them as a collection.

EDIT:

I need the result to be objects (collection) because I also use the code on my view, where I check the class to determine what to display. Also, I use this function to sort the objects in the collection.

    $collection->sort(function($a, $b)
    {
        $a = $a->created_at;
        $b = $b->created_at;
        if ($a === $b) {
            return 0;
        }
        return ($a > $b) ? 1 : -1;
    });
like image 349
user3811576 Avatar asked Sep 26 '14 11:09

user3811576


1 Answers

I know that this is an old question, but I will still provide the answer just in case someone comes here from the search like I did.

If you try to merge two different eloquent collections into one and some objects happen to have the same id, one will overwrite the other. I dunno why it does that and if that's a bug or a feature - more research needed. To fix this just use push() method instead or rethink your approach to the problem to avoid that.

Example of a problem:

$cars = Car::all();
$bikes = Bike::all();
$vehicles = $cars->merge($bikes);
// if there is a car and a bike with the same id, one will overwrite the other

A possible solution:

$collection = collect();
$cars = Car::all();
$bikes = Bike::all();

foreach ($cars as $car)
    $collection->push($car);

foreach ($bikes as $bike)
    $collection->push($bike);

Source: https://medium.com/@tadaspaplauskas/quick-tip-laravel-eloquent-collections-merge-gotcha-moment-e2a56fc95889

like image 183
Tadas Paplauskas Avatar answered Sep 19 '22 20:09

Tadas Paplauskas