title: How to get the count and values of item in a subcategory with parent_id in Laravel
body: <p>How do I get the count and values of all items within a subcategory that has a parent_id. I have a category model which is related to the product model. And in the category table, there are parent_ids and their subcategories. How do I return all the products belonging to a parent category?</p>
  
  <p>The database is shown below
  <a href="https://i.stack.imgur.com/qjMia.png" rel="nofollow noreferrer">Database</a></p>
  
  <p>The Relationships are shown here</p>
  
  <pre class="lang-php prettyprint-override"><code>public function products()
  {
      return $this-&gt;hasMany('App\Product');
  }
  
  public function category()
  {
      return $this-&gt;belongsTo('App\Category');
  }
  </code></pre>
  
  <p>Then in my controller, this returns 0 as count </p>
  
  <pre class="lang-php prettyprint-override"><code>public function niche($url)
  {
      $niche = Category::where('url',$url)-&gt;first();
  
      $categories = Category::where('parent_id',$niche-&gt;id)-&gt;get();
      $products = [];
  
      foreach($categories as $category) {
          $products = Product::where('category_id',$category-&gt;id)-&gt;get();
      }
  
      dd($products-&gt;count());
  }
  </code></pre>
  
  <p><a href="https://i.stack.imgur.com/pVcUq.png" rel="nofollow noreferrer">Output</a></p>
  
  <p>Please how do I get the number of products belonging to this niche?
  Thanks. </p>