Quick tip for those who want to list some events, grouping them by some date value – by day, month, year etc.
Let’s take a look at example – we have this database structure of appointments.
$days = Appointment::whereBetween('start_time', [now(), now()->addDays(7)])
->orderBy('start_time')
->get()
->groupBy(function ($val) {
return Carbon::parse($val->start_time)->format('d');
});
foreach ($days as $day => $appointments) {
echo '<h2>'.$day.'</h2><ul>';
foreach ($appointments as $appointment) {
echo '<li>'.$appointment->start_time.'</li>';
}
echo '</ul>';
}
Reference: https://laraveldaily.com/laravel-group-query-result-by-day-month-year/