Saturday, March 18, 2017

How to get subcategories of category in Laravel?

I have two models: User, Category

Thant to get all categories with parent_id = 0 I use:

$categories = Category::parentcategory()->get();

Where model Category is:

 public function scopeParentCategory($query, $parent = 0)
    {
        return $query->where('parent_id', $parent);
    }

In this model I have also:

public function subcategories()
    {
        return $this->hasMany('App\Category', 'parent_id', 'id');
    }

That should return subcategories of selected above categories. For this I tried:

 public function scopeParentCategory($query, $parent = 0)
        {
            return $query->where('parent_id', $parent)->subcategories();
        }

In the last, I need to count users which subscribed on subcategories of categories, selected above.



via Darama

Advertisement