Laravel Collection Merge | How to Merge Two Eloquent Collection?

Laravel Collection Merge | How to Merge Two Eloquent Collection?

In this post we will give you information about Laravel Collection Merge | How to Merge Two Eloquent Collection?. Hear we will give you detail about Laravel Collection Merge | How to Merge Two Eloquent Collection?And how to use it also give you demo for it if it is necessary.

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 and laravel 7. 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:

IlluminateSupportCollection 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:

IlluminateSupportCollection Object

(

[items:protected] => Array

(

[0] => One

[1] => Two

[2] => Three

[4] => Four

[5] => Five

)

)

Example 3: Laravel Eloquent Merge Collections

Also see:Laravel Collection Unique | Remove Duplicates from Collection Laravel

public function index()

{

$firstCollection = Patient::get();

$secondCollection = User::get();

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

$mergedCollection->all();

}

I hope it can help you…

Hope this code and post will helped you for implement Laravel Collection Merge | How to Merge Two Eloquent Collection?. if you need any help or any feedback give it in comment section or you have good idea about this post you can give it comment section. Your comment will help us for help you more and improve us. we will give you this type of more interesting post in featured also so, For more interesting post and code Keep reading our blogs

For More Info See :: laravel And github

Leave a Comment

Your email address will not be published. Required fields are marked *

51  +    =  58

We're accepting well-written guest posts and this is a great opportunity to collaborate : Contact US