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

Danieloplata's avatar

Group collection results by date

Hi guys,

I'm trying to group a collection by date, so that I can print them to a page by creating a foreach loop per date, rather than per appointment (shown below). I'm not very familiar with the syntax used here, so I worry I might be way off.

This is what I've got so far:

// AppointmentController.index
...
$appointments = Session::get('uniqueid')->appointments()->groupBy('date')->get();

// appointments.blade.php
...
@forelse ($appointments as $appointments->date => $appointment)
    <div class="lg:w-1/3 px-3 pb-6">
        @include ('appointment_times.card')
    </div>
@empty
    <div>No appointments available at the moment. Please check back later.</div>
@endforelse

There are 3 possible appointments per day, over a 7 day period. I want to show 7 of my appointment cards on the page, with the 3 appointments for that day on each.

$appointments = Session::get('uniqueid')->appointments // returns all 21 appointments
$appointments = Session::get('uniqueid')->appointments()->groupBy('date')->get(); // returns all 21 appointments with no grouping

Dates are stored in the database as type date with format YYYY-MM-DD

0 likes
2 replies
Danieloplata's avatar
Danieloplata
OP
Best Answer
Level 15

I managed to get it working by using the link given by @jlrdw

// AppointmentController.index
$days = Session::get('uniqueid')
    ->appointments()
    ->withPivot('completed')
    ->get()
    ->groupBy(function ($val) {
        return Carbon::parse($val->date)->format('d');
    });

// Appointments.blade.php
@forelse ($days as $day => $appointments)
    <div class="lg:w-1/3 px-3 pb-6">
        @include ('appointment_times.card')
    </div>
@empty
    <div>No appointments are available at the moment. Please check back later.</div>
@endforelse

// appointment_times.card
@foreach ($appointments as $appointment)
...
@endforeach
1 like

Please or to participate in this conversation.