Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Haziqasyraff's avatar

How to add a collection to another returned query result?

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!

0 likes
1 reply

Please or to participate in this conversation.