How To Merge Two Eloquent Collections?
Before talking about the merge of two or more collections, let’s introduce you with the Laravel collections.
What is Laravel Collections?
Laravel uses Eloquent ORM (Object-Relational Mapping) to work with the database which returns the result in collections (Illuminate\Support\Collection) class.
Laravel Collection is providing the extended feature to the PHP array with its powerful methods. Laravel collection allows us to filter and modify data by using tons of available methods.
Create custom Laravel collection
We can create custom Laravel collection by using collect() helper function from the array.
$collection = collect([ [ ‘fruit’=> ‘apple’, ‘amount’=> 320 ], [ ‘fruit’=> ‘banana’, ‘amount’=> 70 ], [ ‘fruit’=> ‘grapes’, ‘amount’=> 60 ], ]);
Loop through the collection
As php array, Laravel collections also allow us to loop over them as iterators.
See also: Step by step tutorial to create your first Laravel project
$tasks = App\task::all(); foreach ($tasks as $task) { echo $task->title; }
Boom!! it’s here
Let’s scroll the merge()
The merge() method help us to merge collection or array with the targeted collection.
$array = [‘fruit’=>’apple’]; $collection = collect([‘amount’=>450]);
Don’ts
You can’t do like this:
$new = $array->merge($collection);
Because merge() is the method of collections not array.
Do’s
Yeah! You can do it:
$new = $collection->merge($array);
Now, it will work very well.
And both can be collections:
$collection1 = collect([‘fruit’=>’apple’]); $collection2 = collect([‘amount’=>450]); $new = $collection1->merge($collection2);
Column overwritten issue
If both collections have the same column, may be one or more than one then the collection2 will overwrite collection1.
$collection1 = collect( [‘fruit’=>’banana’, ‘amount’=>70] ); $collection2 = collect( [‘fruit’=>’apple’, ‘amount’=>230] ); $new = $collection1->merge($collection2);
The output will be:
Collection {#219 ▼ #items: array:2 [▼ "fruit" => "apple" "amount" => 230 ] }
Here, you can see collection2 overwrite the collection1’s columns. To prevent this, do the following:
$collection1 = collect([ [‘fruit’=>’banana’, ‘amount’=>70] ]); $collection2 = collect([ [‘fruit’=>’apple’, ‘amount’=>230] ]); $new = $collection1->merge($collection2);
The output will be:
Collection {#219 ▼ #items: array:2 [▼ 0 => array:2 [▼ "fruit" => "banana" "amount" => 70 ] 1 => array:2 [▼ "fruit" => "apple" "amount" => 230 ] ] }
Have you seen the difference? That’s it.
This is just a one way to do it but It can be done with another approach also.
Hope it was worth reading if it is then why not you comment and share it. Trust me your every share and comments are valuable for me.
1 thought on “How To Merge Two Eloquent Collections?”