Answer the question
In order to leave comments, you need to log in
How to get id of all subcategories from category tree?
DB structure. Category Table
id | category_id | title |
Where category_id is the category ID of the parent.
For example, a category with ID 1 has a subcategory, which in turn also has a subcategory with a subcategory.
Please tell me how to get an array with an ID like this:
array('1'=>array('2','3','4'));
Thank you in advance.
Answer the question
In order to leave comments, you need to log in
In general, I found a solution myself:
CONTROLLER
public function getAllCategories(){
$categories = Category::whereNull('category_id')->with('children')->get();
foreach($categories as $category){
$cats[$category->id] = $this->getAllChildrenCats($category);
}
}
public function getAllChildrenCats($category, $catsIds = []){
foreach($category->children as $children){
$catsIds[] = $children->id;
if($children->children){
$catsIds = $this->getAllChildrenCats($children, $catsIds);
}
}
return $catsIds;
}
public function children() {
return $this->hasMany(Category::class, 'category_id')
->with('children');
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question