If only one level it is a simple self referencing belongs to / has many relationship.
Put a parent_id in your categories table. Then in your Category model :
public function parent()
{
return $this->belongsTo('Category', 'parent_id');
}
public function children()
{
return $this->hasMany('Category', 'parent_id');
}
Then you can get the subcategories of a category like this : $subcategories = $category->children.
If you want to avoid to execute one query per category to retrieve its children you can use eager loading :
Now the issue with this is Category 4 and 5 are also displaying as individual, but they lie only in their parent category and are not separate. what could be the solution for this.
@pmall you need to add namespace for your snippet to work. In case you tried the code and got "Class 'Category' not found", add the your namespace to it to solve the error:
public function parent()
{
return $this->belongsTo('App\Category', 'parent_id');
}
public function children()
{
return $this->hasMany('App\Category', 'parent_id');
}