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