Laravel parent / child relationship on the same model
Stefan Bogdanescu
Founder & Senior Architect · 2026-06-29
The Setup And Dummy Data
Firstly, let's set up a model named Category with an appropriate schema that allows for parent and child categories. Here, we have created a hierarchy where each category can be the parent of another category, or it may not have any children. Our example data illustrates two main branches under 'Home', i.e., 'Products' and 'Services'. Moreover, two products ('Product A' and 'Product B') fall under 'Products'.The Desired Output
We want to achieve a result that shows every category along with its parent and child categories, creating a hierarchical representation. The hierarchy should be displayed in such a way that we can easily identify the parent, children, and grandchildren of any given category. We'll see how to use Laravel's eloquent relationships for this purpose.The Defined Relationship
We need to define relationships between our model categories using Laravel's eloquent relationships. Since a category can be a parent of another or a child, we defined two relationship methods in the Category model: children and parent. The code to define the relationship should look like this:php
public function children()
{
return $this->hasMany('Category', 'parent_id', 'cat_id');
}
public function parent()
{
return $this->belongsTo('Category', 'parent_id');
}Querying for Child Objects
Now let's access the data using Laravel's query builder. We start by finding our target Category with the findOrFail method:php
$category = Category::findOrFail($id);php
$children = $category->children();