How to get the ids of all inner sub categories in laravel

Get the ids of all inner sub categories in laravel

Example models,

app/models/Category.php

<?php

class Category extends Eloquent
{
    /**
     * This will relate the current category to the categories having parent_id value as $this->id
     */
    public function children()
    {
        return $this->hasMany('Category', 'parent_id');
    }

    /**
     * This will return the ids array which contains the id of current category, 
     * and all the sub categories even childrens of each sub categories as well like recursive.
     */
   public static function getIds($category, $ids = false)
   {
       $ids[] = $category->id;
       foreach($category->children as $children)
       {
           $ids[] = getIds($category);
       }
       return $ids;
   }
}

// We can call the getIds as $ids = Category::getIds(Category::find(1));

Leave a Reply