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

HUGE_DICK_10_INCHES's avatar

Laravel group by date range

How can I group rows by custom daterange?

$new_period = CarbonPeriod::create($start, $end);

$data = (new Model)->whereBetween(DB::raw('date(start)'), [$new_period->first()->format('Y-m-d'), $new_period->last()->format('Y-m-d')])
 ->select(DB::raw('id, date(start) as day'))
 ->get()->groupBy('day');

This works but for each day that is not inside database but it is in $new_period range it gets skipped. I can do it with loops and create new collection or whatever. But I am wondering can I use something like:

->groupBy(['01/01/2019','02/01/2019','03/01/2019','04/01/2019','05/01/2019','06/01/2019','07/01/2019'])

By using carbonperiod

0 likes
1 reply
bobbybouwmann's avatar

You can use mapToGroups here as well

$data = (new Model)
    ->whereBetween(DB::raw('date(start)'), [$new_period->first()->format('Y-m-d'), $new_period>last()->format('Y-m-d')])
    ->select(DB::raw('id, date(start) as day'))
    ->get()
    -> mapToGroups(function ($item, $key) {
        return [$item['day'] => $item;
    });

Documentation: https://laravel.com/docs/5.8/collections#method-maptogroups

Please or to participate in this conversation.