How to properly merge multiple collections in Laravel
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);
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(...);
I used ->merge()
but faced a small issue. So I'm adding this in case anyone else face the same issue. ->concat()
is a better solution on database collection merging.
$allItems = new \Illuminate\Database\Eloquent\Collection;
$allItems = $allItems->concat($collection1);
$allItems = $allItems->concat($collection2);
The reason for this is when merging they take ID of the table as the key. So if two tables have two records with same table id ->merge()
will add only one record to $allItems
. But ->concat()
will add two records as they should.