Level 88
You can use merge to merge the two collections together. Not sure if that is what you're after
$collection->merge($collection2);
Documentation: https://laravel.com/docs/7.x/collections#method-merge
1 like
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
Here I have this eloquent query:
$supplierCoverages = SupplierCoverage::whereIn('supplier_id', $supplierListing)
->leftJoin('areas', 'supplier_coverages.area_id', '=', 'areas.id')
->leftJoin('regions', 'areas.region_id', '=', 'regions.id')
->get()
->sortBy('name')
->groupBy(['name', 'areas.name']);
It returns something like this:
{
"Johor": {
"Johor Bahru": [
{
"id": 1,
"supplier_id": 457,
"area_id": 17,
"created_at": "2020-04-21T09:00:16.000000Z",
"updated_at": "2020-04-21T09:00:16.000000Z",
"region_id": 1,
"name": "Johor",
"areas": {
"id": 17,
"region_id": 1,
"name": "Johor Bahru",
"created_at": "2020-04-21T09:11:07.000000Z",
"updated_at": "2020-04-21T09:11:07.000000Z"
}
}
]
}
}
Since Johor Bahru is from Area table which is made by using the eloquent groupBy, I want to return another collection from a table called Runners for the runners available only for that area. So i want something like:
{
"Johor": {
"Johor Bahru": [
{
"id": 1,
"supplier_id": 457,
"area_id": 17,
"created_at": "2020-04-21T09:00:16.000000Z",
"updated_at": "2020-04-21T09:00:16.000000Z",
"region_id": 1,
"name": "Johor",
"areas": {
"id": 17,
"region_id": 1,
"name": "Johor Bahru",
"created_at": "2020-04-21T09:11:07.000000Z",
"updated_at": "2020-04-21T09:11:07.000000Z"
}
}
],
[
{
"id": 1
"runner_id": 123
"name": John Cena
},
{
"id": 2
"runner_id": 213
"name": John Seen
},
]
}
}
The first collection of the area are suppliers, while the second collection of the area are runners. Appreciate your help!
You can use merge to merge the two collections together. Not sure if that is what you're after
$collection->merge($collection2);
Documentation: https://laravel.com/docs/7.x/collections#method-merge
Please or to participate in this conversation.