title: Laravel Nested Children Count (Categories)
body: <p>I using nested categories on my Laravel site with an adjacentcy list style mysql table layout. There is a maximum of 7 layers of categorization, (using <a href="https://www.google.com/basepages/producttype/taxonomy-with-ids.en-US.txt" rel="nofollow noreferrer">google categories taxonomy</a>). Please see the image below for a small sample of data, and the code below for my Category model's relationships.</p>
  
  <p>Each category has zero to many subcategories (using same Category Model), as well as zero to many pages underneath it. <strong>My goal here is to find a way to get a count of all pages beneath a category (including pages under its subcategories).</strong></p>
  
  <p><a href="https://i.stack.imgur.com/hqfsg.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/hqfsg.png" alt="MySql Table Layout Example"></a></p>
  
  <p>My Category model has the following relationships which are all functioning:</p>
  
  <pre><code>public function pages() {
      return $this-&gt;hasMany('App\Models\Page');
  }
  
  public function children() {
      return $this-&gt;hasMany('App\Models\Category', 'parent_id' );
  }
  
  public function parent() {
      return $this-&gt;belongsTo('App\Models\Category', 'parent_id' );
  }
  
  public function childrenRecursive() {
     return $this-&gt;children()-&gt;orderBy( 'name' )-&gt;with('childrenRecursive', 'pages');
  }
  
  public function parentRecursive() {
     return $this-&gt;parent()-&gt;with('parentRecursive');
  }
  </code></pre>