title: How to count products in parent category via child categories having nested relationtionship(belongsToMany) using eloquent
body: <p>I am trying to count all active products in parent category. A parent category has many child categories(only one level deep). A product can be assigned to multiple child categories but not parent category.</p>
  
  <p>For ex. I have "Toys"(parent) category having 3 child categories "for boys"(having 5 products), "for girls" (having 6 products), "for teens" (having 12 products).</p>
  
  <p>My sidebar menu at homepage have all the parent categories and wants to show product count of respective parent category using eloquent way. The eloquent query is being used in view composer.</p>
  
  <p>Using above example, I want to show like:</p>
  
  <pre><code>Toys  23 (5 + 6 + 12 = 23 after totaling products from child categories)  
  
  Games 10
  
  Sports 15
  
  and so on..
  </code></pre>
  
  <p>I want to get parent category with product count, and not child categories details. </p>
  
  <p>My Category.php Model</p>
  
  <pre><code>public function parent() {
      return $this-&gt;belongsTo(self::class, 'parent_id');
  }
  
  public function children() {
      return $this-&gt;hasMany(self::class, 'parent_id', 'id');
  }
  
  public function products() {
      return $this-&gt;belongsToMany('App\Product');
  }
  </code></pre>
  
  <p>My Product.php Model</p>
  
  <pre><code>public function categories() {
      return $this-&gt;belongsToMany('App\Category');
  }
  
  public function user() {
      return $this-&gt;belongsTo('App\User');
  }
  </code></pre>
  
  <p>Queries I have tried</p>
  
  <pre><code>Category::select('id', 'parent_id', 'slug' ,'name')-&gt;where(['active' =&gt; 1, 'parent_id' =&gt; null])-&gt;with(['children' =&gt; function($query) {
          $query-&gt;withCount('products');
      }])-&gt;get();
  </code></pre>
  
  <p>This give me product count of children. I can loop through children and can add total product for parents. But, doesn't seems me a good way, since this loads child categories data too which I don't need. I have a total of around 400 categories.</p>
  
  <pre><code>Category::select('id', 'parent_id', 'slug' ,'name')-&gt;where(['active' =&gt; 1, 'parent_id' =&gt; null])-&gt;with('children')-&gt;withCount('products')-&gt;get();
  </code></pre>
  
  <p>This gives product count as 0, obviously as parent category has no product assigned to it.</p>
  
  <p>I see a lot of examples her using withCount, but they all explains hasManyThrough relations. I am having belongsToMany relation set up in Category and Product Model. Guide me if withCount is implemented in belongsToMany relation anywhere.</p>
  
  <p>I am looking for optimized database queries to get the result I need. Please let me know your thought.</p>
  
  <p>Thanks a lot for your valuable time.</p>