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

Jakub003's avatar

How to order or sort when using groupBy on eloquent collection

I was wondering if I could get some help with sorting the groups.

I am trying to create a time tracker, group the sessions by the dates, and order them. It looks something like this.

Still learning how this groupBy works, first time using it.

I came across this Laravel Daily video on it, and I am trying to use the first approach with laravel query.

My code looks like this


$sessionDays = TaskTimeSession::where('user_id', $userId)
                                            ->with('task')
                                            ->get()
                                            ->groupBy(function($date) {
                                                $currentDate = $date->updated_at->format('Y-m-d');
                                                return  $currentDate;
                                            })
                                            ->map(function ($sessionDays) {
                                                return $sessionDays;
                                            });

In the blade file

@forelse ($sessionDays as $date => $taskSessions)
	<div>
	     ...
        @foreach ($taskSessions as $taskSession)
             <x-time-tracking-card />
         @endforeach
	 </div>
@empty
      <p>No Sessions Found</p>
@endforelse

the dd($sessionDays) looks like this

Any help or insight much appreciated :)

0 likes
2 replies
Jakub003's avatar

I did try using sortyBy (date) and updated_at, but it didn't sort it at all

Jakub003's avatar
Jakub003
OP
Best Answer
Level 7

lol i am a newb, i got it working .Did not realize you could orderby directly before you map and it does the same thing

Please or to participate in this conversation.