title: Laravel Eloquent subquery and count subquery results
body: <p>Let's say there's a <code>Post</code> model. It has a <code>hasMany</code> relationship called <code>comments()</code> defined in its model.</p>
  
  <p>I'm trying to:</p>
  
  <ul>
  <li>Get the count of comments</li>
  <li>That belongs to a specific set of Posts, defined by an array of ids</li>
  <li>Where the comments are posted in a certain date range</li>
  </ul>
  
  <p>I thought the following would work:</p>
  
  <pre><code>$ids = [1, 2, 3, 4];
  
  $results = Post::whereIn('id', $ids)
      -&gt;with(['comments'])
      -&gt;whereHas('comments', function($q) {
         $q-&gt;whereMonth('created_at', Carbon::now()-&gt;month);
      })
      -&gt;withCount('comments')
      -&gt;get();
  </code></pre>
  
  <p>And then do</p>
  
  <pre><code>$count = array_sum($results-&gt;pluck('comments_count')-&gt;toArray());
  </code></pre>
  
  <p>The result of the query does include <code>comments_count</code> so that's working, and <code>$count</code> works as well.</p>
  
  <p>But the date range in the subquery is not applied, it counts <em>all</em> comments. What am I missing?</p>