W
W
websolab2021-09-14 00:00:43
Arrays
websolab, 2021-09-14 00:00:43

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.

613fbc2977eb5873715260.png

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

1 answer(s)
W
websolab, 2021-09-14
@websolab

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; 
  
    }

MODEL
public function children() {
        return $this->hasMany(Category::class, 'category_id')
          			->with('children');
    }

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question