Laravel Eloquent collections merge() “gotcha” moment

Laravel collections are a powerful tool to process data, but it comes with a few gotchas. Today I spent far too much time on one of those moments.

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. Use push() method instead or rethink your approach to the problem to avoid that.

Example of a problem:

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

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);
    

Keep up with me

If you like what I do, consider subscribing. There's also RSS feed, if you prefer that.

Wanna reach out? Tweet at me or drop me an email: tl.saksualpap@olleh.

2011-2021