Support the ongoing development of →
Last updated 1 month ago.

for the date filtering you can make a scope. For example scopeInMonth($year, $month).

I didn't try the query, but it should be along these lines

User::withCount('comments', function ($commentQuery){return $commentQuery->inMonth(2019,12)->groupBy('commentable_id', 'commentable_type', 'user_id');})->get();

Also be aware that grouping by commentable_id isn't enough. Anything could be commentable and the IDs can overlap. Like a commentable Post and commentable Comment can have the same ID, in which case they get counted together.

Last updated 2 years ago.

Be aware that this will execute two queries, one to fetch the users and the the other to fetch the comment count. You will probably add more wheres to the main query. More details at


Error Code: 1242. Subquery returns more than 1 row


Can you log and post the resulting query here?


SELECT id, name, (SELECT COUNT(*) FROM>= '2019-12-01' ANDcreated_at<= '2019-12-31' GROUP BYcommentable_id,commentable_type,user_id) AS comments_countFROMusersWHEREusers.deleted_at IS NULL

Last updated 2 years ago.

Instead of two nested subqueries you should go for 'count (distinct commentable_id, commentable_type)'. That should be faster. Drop the group by. Not sure how to acheieve it in Eloquent. Try to replace groupBy with distinct.


Here's my two cents (not looking at performance). By the way this is wat Laravel docs says about it:

$users = User::query()->withCount(['comments' => function(Builder $query) {
    $query->whereMonth('created_at', '6');

echo $users[0]->comments_count;

This will build this query (i simplified it):

  (select count(*) from `comments` where `users`.`id` = `comments`.`user_id` and month(`created_at`) = 6) as `contracts_count` 
from `employees`
Last updated 2 years ago.

I used fromSub method, I think it's the best way


Looks like a solid solution. Thanks for sharing this.


This very great information for me thanks for sharing ....i helped me a lot FE

Last updated 1 year ago.

Sign in to participate in this thread!


Your banner here too?


We'd like to thank these amazing companies for supporting us

Your logo here?

The Laravel portal for problem solving, knowledge sharing and community building.

© 2022 - All rights reserved.