Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

princeoo7's avatar

Eloquent with, withCount gives 12 as total records but the function with groupby on date gives 9

I have 3 tables, Users, Tasks, TasksSession.

what I am trying to find is total session conducted and total days the user was involved in that task based on created_at group by statement.


    User::with(['Task','TotalSessionsGroupByDate'])->withCount(['TotalSessions','TotalSessionsGroupByDate'])->whereId(2)->first(),


With the above total_sessions_group_by_date_count = 12 and total_sessions_group_by_date_count = 9 records in an array.

function code for the TotalSessionsGroupByDate is as followed


    public function TotalSessionsGroupByDate(){
        return $this->hasMany(TaskSession::class)->groupBy('created_at');
    }

I have the total number of the session conducted / attendance but how to get the total number of days irrelevant to sessions. as per the example, total_sessions_group_by_date_count should be 9 and not 12 total_sessions_group_by_date_count.

the only solution that i was as of now, able to come up is as below:


$user = User::with(['TaskIssues','TotalSessionsGroupByDate'])
                        ->withCount(['TotalSessions'])
                        ->whereId(16)->first();
        $user->TotalSessionsGroupByDate = $user->TotalSessionsGroupByDate->count();

any better way to do the same in model?

0 likes
4 replies
princeoo7's avatar

can you give me an example for my case as still confused over how I should use the resources as I have never used it...

Wraith's avatar

Where is your file with DB dump ?

Please or to participate in this conversation.