Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to properly merge multiple collections in Laravel

I want to merge multiple collections into one. I do have a solution, which is the following:

$allItems = $collection1->merge($collection2)                         ->merge($collection3)                         ->merge($collection4)                         ->merge($collection5); 

This actually does work, but I run into problems in cases where some or all of the collections contain no objects. I get an error along the lines of call to merge() on non object.

I actually tried to create an array of all of the collections, and then iterate through them, while checking their validity, but it didn't work and I feel it wasn't very elegant.

How can I elegantly iterate through this process of merging multiple collections, while taking into account that some or all of the collections might be empty or invalid? Appreciated!

like image 664
Marcel Gruber Avatar asked Sep 04 '15 00:09

Marcel Gruber


People also ask

How do I combine two collections in laravel?

Laravel collection merge() method merge any given array to first collection array. If the first collection is indexed array, the second collection will be added to the end of the new collection. The merge() method can accept either an array or a Collection instance.

How do I merge objects in laravel?

You could simply use array_merge(firstObject,secondObject) function.

What is difference between Collection and array in laravel?

An Array is a basic data structure that stores one or many items in a single variable. PHP arrays have a massive problem with not being OOP. Illuminate\Support (Laravel) Collection comes with help. Laravel Collection is a fluent OOP wrapper for working with arrays.


2 Answers

What I ended up doing was separating each step. It was the merge chaining that was killing it, because some or all of the collections could have been invalid.

$allItems = new \Illuminate\Database\Eloquent\Collection; //Create empty collection which we know has the merge() method $allItems = $allItems->merge($collection1); $allItems = $allItems->merge($collection2); $allItems = $allItems->merge($collection3); $allItems = $allItems->merge($collection4); 
like image 93
Marcel Gruber Avatar answered Oct 08 '22 21:10

Marcel Gruber


I had the same question, so I solved it in the following way:

$clients = ClientAccount::query()->get(); $admins = AdminAccount::query()->get();  $users = collect($clients)->merge($admins)->merge($anotherCollection)->merge(...); 
like image 44
Leonid Dashko Avatar answered Oct 08 '22 19:10

Leonid Dashko