How to create a nested-list of categories in Laravel?
If someone needs a better answer look up my answer, it helped me, when I had faced with such a problem.
class Category extends Model {
private $descendants = [];
public function subcategories()
{
return $this->hasMany(Category::class, 'parent_id');
}
public function children()
{
return $this->subcategories()->with('children');
}
public function hasChildren(){
if($this->children->count()){
return true;
}
return false;
}
public function findDescendants(Category $category){
$this->descendants[] = $category->id;
if($category->hasChildren()){
foreach($category->children as $child){
$this->findDescendants($child);
}
}
}
public function getDescendants(Category $category){
$this->findDescendants($category);
return $this->descendants;
}
}
And In your Controller just test this:
$category = Category::find(1);
$category_ids = $category->getDescendants($category);
It will result ids in array all descendants of your category where id=1. then :
$products = Product::whereIn('category_id',$category_ids)->get();
You are welcome =)
You can make a self-referential model:
class Category extends Model {
public function parent()
{
return $this->belongsTo('Category', 'parent_id');
}
public function children()
{
return $this->hasMany('Category', 'parent_id');
}
}
and make a recursive relation:
// recursive, loads all descendants
public function childrenRecursive()
{
return $this->children()->with('childrenRecursive');
}
and to get parents with all their children:
$categories = Category::with('childrenRecursive')->whereNull('parent_id')->get();
Lastly you need to just iterate through the children until children is null. There can definitely be some performance issues with this if you are not careful. If this is a fairly small dataset that you plan to remain that way it shouldn't be an issue. If this is going to be an ever growing list it might make sense to have a root_parent_id
or something to query off of and assemble the tree manually.
This function will return tree array:
function getCategoryTree($parent_id = 0, $spacing = '', $tree_array = array()) {
$categories = Category::select('id', 'name', 'parent_id')->where('parent_id' ,'=', $parent_id)->orderBy('parent_id')->get();
foreach ($categories as $item){
$tree_array[] = ['categoryId' => $item->id, 'categoryName' =>$spacing . $item->name] ;
$tree_array = $this->getCategoryTree($item->id, $spacing . '--', $tree_array);
}
return $tree_array;
}