Rediska's avatar

How to combine multiple collections into one?

Hello everyone, forum users! Can you please tell me how to merge several collections into one? There are several tables, identical in columns - color, gender, material. I use a many-to-many relationship. To get one of them I do this:

$colors = Color::withTrashed()
            ->orderBy('id', 'desc')
            ->paginate('10');
$genders = Gender::withTrashed()
            ->orderBy('id', 'desc')
            ->paginate('10');

How can I get one collection with all data? For example, enter a new variable $allParameters = ???

0 likes
3 replies
LaryAI's avatar
LaryAI
AI
Best Answer
Level 58

To combine multiple collections into one, you can use the concat method provided by Laravel's Collection class. Here's an example:

$colors = Color::withTrashed()
            ->orderBy('id', 'desc')
            ->paginate('10');

$genders = Gender::withTrashed()
            ->orderBy('id', 'desc')
            ->paginate('10');

$allParameters = $colors->concat($genders);

This will create a new collection that contains all the items from both $colors and $genders. You can continue to chain methods onto $allParameters just like any other collection.

1 like
Rediska's avatar

$allParameters = $colors->concat($genders);

Please or to participate in this conversation.