Nitin Johnson
Nitin Johnson

Reputation: 340

How to get all the sub category ids in laravel based on the category id?

I am trying to get all the sub category ids recursively from the top level category to its bottom most sub category. I have set a parent id for every category, for the top most category I am using zero as the parent category. I am getting the list of sub categories but not all of them. Please help.

Controller Code

public function index($slug){ 
    $category=Category::where('category_slug',$slug)->first();
    if(!empty($category)){
        $category_ids=$this->GetAllChildCategoryIDS($category->id);                
        dd($category_ids);
    }       
}

public function GetAllChildCategoryIDS($category_id) {
    $ids_array = Category::where('parent_id',$category_id)->pluck('id')->all();
    foreach($ids_array as $ida) {
        $temp_ids=$this->GetSubCategoryIDS($ida);
        if(count($temp_ids)) {
            $ids_array[]=$temp_ids;
        }
    }  
        
    if(!empty($ids_array)) {
        $ids_array=$this->array_flatten($ids_array);
    }    
    return $ids_array;
}

public function GetSubCategoryIDS($category_id) {
    $ids_array = Category::where('parent_id',$category_id)->pluck('id')->all();
    return $ids_array;
}

public function array_flatten($array) { 
    if (!is_array($array)) { 
        return FALSE; 
    } 
    $result = array(); 
    foreach ($array as $key => $value) { 
        if (is_array($value)) { 
            $result = array_merge($result, $this->array_flatten($value)); 
        } else { 
            $result[$key] = $value; 
        } 
    } 
    return $result; 
}

Result

array:20 [▼
  0 => 22
  1 => 23
  2 => 24
  3 => 25
  4 => 26
  5 => 27
  6 => 35
  7 => 36
  8 => 37
  9 => 38
  10 => 39
  11 => 40
  12 => 41
  13 => 28
  14 => 29
  15 => 30
  16 => 31
  17 => 32
  18 => 33
  19 => 34
]

Upvotes: 0

Views: 1220

Answers (1)

Mathieu Ferre
Mathieu Ferre

Reputation: 4412

You can use a recursive relationship a so :


public function childs(){
    return $this->hasMany(Category::class);
}

public function recursiveChilds(){
   return $this->childs()->with('recursiveChilds');
}

then you can access any n-level of childs :

foreach($category->recursiveChilds as $level_1_child){
     foreach($level_1_child->recursiveChilds as $level_2_child){
         [...]
     }
}

if you want a collection of ALL the childs, you can use this :

public static function flattenChilds($parent)
    {
        $result = collect([]);
        foreach ($parent->recursiveChilds as $child) {
            $result->push($child);
            $result = $result->merge(static::flattenChilds($child));
        }

        return $result->filter();
    }

Upvotes: 2

Related Questions