ItSolutionStuff.com

Laravel Collection Merge | How to Merge Two Eloquent Collection?

By Hardik Savani • April 16, 2024
Laravel

Hello Dev,

In this quick example, let's see laravel collection merge example. Here you will learn laravel collection merge by value. In this article, we will implement a laravel eloquent merge collections. you will learn eloquent merge collections.

I will explain you step by step example how to user merge collection in laravel. i will also give you example how to merge collection with unique in laravel 6, laravel 7, laravel 8, laravel 9, laravel 10 and laravel 11. i will also give you example of how to merge two eloquent laravel collection.

So, let's see bellow example.

Example 1:

public function index()

{

$firstCollection = collect(['One', 'Two', 'Three']);

$secondCollection = collect(['Four', 'Five']);

$mergedCollection = $firstCollection->merge($secondCollection);

$mergedCollection->all();

dd($mergedCollection);

}

Output:

Illuminate\Support\Collection Object

(

[items:protected] => Array

(

[0] => One

[1] => Two

[2] => Three

[3] => Four

[4] => Five

)

)

Example 2: Laravel Collection Merge Unique

public function index()

{

$firstCollection = collect(['One', 'Two', 'Three']);

$secondCollection = collect(['Three', 'Four', 'Five']);

$mergedCollection = $firstCollection->merge($secondCollection);

$mergedCollection = $mergedCollection->unique(function ($item) {

return $item;

});

$mergedCollection->all();

dd($mergedCollection);

}

Output:

Illuminate\Support\Collection Object

(

[items:protected] => Array

(

[0] => One

[1] => Two

[2] => Three

[4] => Four

[5] => Five

)

)

Example 3: Laravel Eloquent Merge Collections

public function index()

{

$firstCollection = Patient::get();

$secondCollection = User::get();

$mergedCollection = $firstCollection->merge($secondCollection);

$mergedCollection->all();

}

I hope it can help you...

Hardik Savani

Hardik Savani

I'm a full-stack developer, entrepreneur, and founder of ItSolutionStuff.com. Passionate about PHP, Laravel, JavaScript, and helping developers grow.

📺 Subscribe on YouTube

We Are Recommending You

Laravel Collection Search Method Example

Read Now →

Laravel Collection Filter Method Example

Read Now →

Laravel 8/7 Paginate with Collection or Array

Read Now →

Laravel Order By Relationship Sum Column Example

Read Now →

Laravel Relationship Eager Loading with Count Example

Read Now →

Merge Multiple Collection Paginate in Laravel

Read Now →

Laravel Relationship Where Condition Example

Read Now →

Laravel One to One Eloquent Relationship Tutorial

Read Now →