How to Merge Two Collection in Laravel 12

In this tutorial, I’ll show you how to merge two Eloquent collections in Laravel 12 using the merge() method. This is useful when you want to combine results from two different queries or models. I’ll share different examples, like merging same or different model collections, removing duplicates, and reindexing results.

How to Merge Two Eloquent Collections in Laravel 12

Laravel provides the merge() method to combine two collections into one. This is especially handy when working with Eloquent query results.

How to Merge Two Eloquent Collections in Laravel 12

 

Example 1: Merge Collections from Same Model

$usersA = User::where('role', 'admin')->get();
$usersB = User::where('role', 'editor')->get();

$merged = $usersA->merge($usersB);

dd($merged);

 

Example 2: Merge and Reindex Collection

$usersA = User::where('role', 'admin')->get();
$usersB = User::where('role', 'editor')->get();

$merged = $usersA->merge($usersB)->values();

dd($merged);

 

Example 3: Merge Different Models

$posts = Post::all();
$videos = Video::all();

$merged = $posts->merge($videos);

dd($merged);

 

Example 4: Merge and Remove Duplicates

$usersA = User::where('status', 'active')->get();
$usersB = User::where('status', 'pending')->get();

$merged = $usersA->merge($usersB)->unique('id')->values();

dd($merged);

 

Example 5: Merge Collections with Custom Keys

$collection1 = collect(['a' => 'apple', 'b' => 'banana']);
$collection2 = collect(['b' => 'blueberry', 'c' => 'cherry']);

$merged = $collection1->merge($collection2);

dd($merged);
// Output: ['a' => 'apple', 'b' => 'blueberry', 'c' => 'cherry']

 

Example 6: Merge Simple Collection

$one = collect(['One', 'Two', 'Three']);
$two = collect(['Four', 'Five']);

$mergedCollection = $one->merge($two);
$mergedCollection->all();

dd($mergedCollection);

 

Example 7: Merge Unique Collection

$one = collect(['One', 'Two', 'Three']);
$two = collect(['Three', 'Four', 'Five']);

$mergedCollection = $one->merge($two);
$mergedCollection = $mergedCollection->unique(function ($item) {
   return $item;
});

$mergedCollection->all();
dd($mergedCollection);

 


You might also like:

techsolutionstuff

Techsolutionstuff | The Complete Guide

I'm a software engineer and the founder of techsolutionstuff.com. Hailing from India, I craft articles, tutorials, tricks, and tips to aid developers. Explore Laravel, PHP, MySQL, jQuery, Bootstrap, Node.js, Vue.js, and AngularJS in our tech stack.

RECOMMENDED POSTS

FEATURE POSTS