Level 4
Found the solution. Just need to nest eager loading with dot notation
public function categories()
{
return Category::with('sub_categories.sub_categories')
->where('parent_id', null)->get();
}
1 like
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
Hi there, I'm trying to make a 3 levels category API. I already can get two levels using Eager Loading.
public function categories()
{
return Category::with('sub_categories')
->where('parent_id', null)->get();
}
In Laravel Blade I could use count(sub_category->sub_categories) in a condition block which I can't use it in Vue.js. I think I need to have complete object of categories instead.
I now have
[
{
"id": 1,
"name": "Parent Category",
"parent_id": null,
"sub_categories": [
{
"id": 2,
"name": "Sub Category",
"parent_id": 1,
}
]
}
]
which should be something like:
[
{
"id": 1,
"name": "Parent Category",
"parent_id": null,
"sub_categories": [
{
"id": 2,
"name": "Sub Category",
"parent_id": 1,
"sub_categories": [
{
"id": 3,
"name": "Sub sub Category",
"parent_id": 2,
}
]
}
]
}
]
I think I should use some functions like map(), filter(), each() but I don't know how!
Any help would be so greatly appreciated...
Found the solution. Just need to nest eager loading with dot notation
public function categories()
{
return Category::with('sub_categories.sub_categories')
->where('parent_id', null)->get();
}
Please or to participate in this conversation.