How to merge two eloquent collections in Laravel

In this simple tutorial of how to merge two eloquent collections in Laravel I will show you how to merge two or more eloquent collections. In this example you may try to merge two different collection resulting from the instance of the same model only.

Merging two or more collections coming from different models is not discussed in this post. Keep reading if you want to merge collection of results from same model.

So let’s jump into the code now.

$programs = collect();
$programsCreatedToday = \App\Models\Program::whereDate('create_at', '=', Carbon::today())->get();
$programsModifiedToday = \App\Models\Program::whereDate('updated_at', '=', Carbon::today())->get();
$programs = $programs->merge($programsCreatedToday)->merge($programsModifiedToday);

In another example I will show you how to merge two or more eloquent collections inside a for-loop.

In this example I have two models named Program and Domain. Every Program is tied with belongsToMany relation to Domain and vice versa. Relationship is not important in this example and I am just showing if for the sake of a more practical example of foreach loop in Laravel application.

$programs = collect();
$domains = Domain::where([])->get();
foreach( $domains as $domain)   {
    if( !$domain->programs->isEmpty() )   {
        $programs = $programs->merge( $domain->programs );
    }
}

The resulting $programs variable is the merged collection of all the collections of programs found in the foreach loop of all the domain. In similar way you can merge two or more eloquent collections in Laravel.

One thing to note in the case of foreach loop is, that you must assign the merged collection to itself after merge. It is easier to make this mistake to write the line 5 this like:

$programs->merge( $domain->programs );

Be aware of it. I have made this mistake and I hope you don’t :)

I hope you find “merge two eloquent collections in Laravel article” useful!

Leave a Reply