How can I create a nested list of categories in Laravel?
I want to create something like this:
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 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 =)