Skip to main content

Black Friday 2025! Only until December 1st: coupon FRIDAY25 for 40% off Yearly/Lifetime membership!

Read more here
Tutorial Free

Laravel Group Query Result by Day/Month/Year

November 18, 2018
2 min read

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.

And we want to list the upcoming appointments for 7 days ahead, grouped by day. Like this:

Ok, so here's the code:

$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>';
}

A few explanations here:

  1. The main “trick”: you can use Collection result to groupBy any custom logic you want – see groupBy(function ($val) { …
  2. Inside of that groupBy we still need to use Carbon::parse(), even if start_time column is within $dates array of the model.
  3. Use now() helper to manipulate some dates

That’s it! You can read more about available Collection grouping/manipulating methods in the official documentation, or purchase my course “Eloquent: Expert Level”, where I dedicated one of the sections to Collections.

Enjoyed This Tutorial?

Get access to all premium tutorials, video and text courses, and exclusive Laravel resources. Join our community of 10,000+ developers.

Comments & Discussion

No comments yet…

We'd Love Your Feedback

Tell us what you like or what we can improve

Feel free to share anything you like or dislike about this page or the platform in general.