Checkout https://laravel.com/docs/5.7/eloquent-resources#writing-resources
I would not do grouping on the backend cause that is more presentation layer requirement but move it to frontend.
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
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?
Please or to participate in this conversation.