You could eager load them on the relation of the parent model.
$category = Category::where('id', $categoryId)->with('subcategory')
->firstOrFail();
That should make them available within the same object.
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
I made a simple API to return category child which displays the JSON output like below:
[
{
"id": 14,
"name": "Pillows",
"slug": "pillows",
"parent_category_id": 1,
"created_at": "2020-04-30 09:33:31",
"updated_at": "2020-04-30 09:33:31"
},
{
"id": 15,
"name": "Bedsheets",
"slug": "bedsheets",
"parent_category_id": 1,
"created_at": "2020-04-30 09:33:31",
"updated_at": "2020-04-30 09:33:31"
},
{
"id": 16,
"name": "Mattresses",
"slug": "mattresses",
"parent_category_id": 1,
"created_at": "2020-04-30 09:33:31",
"updated_at": "2020-04-30 09:33:31"
},
{
"id": 17,
"name": "Bedframes",
"slug": "bedframes",
"parent_category_id": 1,
"created_at": "2020-04-30 09:33:31",
"updated_at": "2020-04-30 09:33:31"
}
]
The code of controller is basically like below:
/**
* Return category with products, product images, product sold by panels.
*/
public function getChildCategory(Request $request, $categoryId)
{
try {
$category = Category::where('id', $categoryId)
->firstOrFail();
}
// catch(Exception $e) catch any exception
catch (ModelNotFoundException $e) {
$error = 'The requested resource is not available.';
return $this->sendError($error, 404);
}
$childCategories = $category->childCategories;
return $this->sendResponse($childCategories);
}
However, I want to add sub object within the object like below:
{
"id": 14,
"name": "Pillows",
"slug": "pillows",
"parent_category_id": 1,
"created_at": "2020-04-30 09:33:31",
"updated_at": "2020-04-30 09:33:31"
Product: (
color:black,
item:phone
)
},
How do I hardcode it so that I can display this for testing purposes?
Laravel uses Eloquent Query Builder - this builds up a query based on the information you give it, and it returns a "Collection" A collection contains the information you requested.
So your first query:
$category = Category::where('id', $categoryId)->firstOrFail();
will return a collection of categories.
Your second query is on the relationship:
childCategories = $category->childCategories
This returns a collection which contains the childCategories. All I have done it told Eloquent, that I would like it to load the products relation on the category too. So the collection it returns will include the related products.
$childCategories = $category->childCategories->load('products');
I have told it to load products products being the relationship in the model you shared above.
This particular way of loading a relationship is called lazy loading. For more information about loading relationships on models, you can view the documents here: https://laravel.com/docs/7.x/eloquent-relationships#eager-loading
Please or to participate in this conversation.