Last Updated: February 25, 2016
·
15.09K
· searsaw

Adding Items to Laravel 4 Collections

Collections in Laravel have a ton of undocumented functions that can come in handy someday. One such function is the merge() function. It will merge a collection, a class that implements the ArrayableInterface, or an array into another collection and return a single collection containing all the elements in the two objects. This will come in handy when combining the results of two database queries together.

$users = User::where('name', '!=', 'Frank')->get();
$cars = Car::where('color', '=', 'blue')->get();
$combo = $users->merge($cars);

5 Responses
Add your response

Hi there. On Laravel 4.1 this doesn't really seem to work?

I get an exception

Call to undefined method Illuminate\Database\Query\Builder::merge()

and if I add ->get() to the first two lines (to actually receive a Collection for each model) then the resulting merged Collection is unique on the array keys (thus returning only one entry per id = 1 for instance)... Can you confirm?

over 1 year ago ·

I forgot to call get() on the builders to get the collections. Thanks for pointing that out.

Also, looking at the source code, it looks like it's now implemented to only have unique keys. This makes some sense if you make the assumption that you would be merging two collections of the same model type. Also assuming your keys are your primary keys in the DB, then they wouldn't overwrite each other. It would preserve the keys of the rows in the DB and merge them correctly. Things break down once you start merging collections of different models. This is a Laravel feature and may be something to introduce on the Github repo as an issue.

over 1 year ago ·

Agreed. Thanks for the follow-up.
Not sure if this may help, but In the end what I ended up doing is to create and return a Eloquent\Collection object to which I'm adding the various models manually (using $newCollection->add() ) .
That works, the only caveat being to reset the array keys before returning with a $newCollection->values() call.

over 1 year ago ·

Does this function deduplicate objects that already exist?

over 1 year ago ·

yes it does. i'm looking for a way to add objects to collection without the deduplication

over 1 year ago ·