Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save mknparreira/54c87cd99b2b69ab21a6de38d45fe61b to your computer and use it in GitHub Desktop.
Save mknparreira/54c87cd99b2b69ab21a6de38d45fe61b to your computer and use it in GitHub Desktop.
Laravel | Group query result by day month year

Introduction

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>';
}
@mknparreira
Copy link
Author

Screen-Shot-2018-11-18-at-9 37 25-AM

@mknparreira
Copy link
Author

Screen-Shot-2018-11-18-at-9 41 40-AM

@mknparreira
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment