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

GodziLaravel's avatar

How to group by date

Hello ,

I would like to group the model results (created_at) by date Y-m-d instead of timestamp.

but this is not working !

$groupdays = CompetenceLog::orderBy('created_at')
            ->groupBy(function ($val) {
                return Carbon::parse($val->created_at)->format('d');
            });
0 likes
4 replies
Sinnbeck's avatar

Get the results first

$groupdays = CompetenceLog::orderBy('created_at')->get()
            ->groupBy(function ($val) {
                return $val->format('Y-m-d');
            });
GodziLaravel's avatar

thanks @sinnbeck it works,

Now I would like to make a kind of pagination , each page has 'n' days (n=3 for this example)

user sends the page number then I could calculate the segment date

example : if page is 2 ===> ['2019-11-16' to '2019-11-14']

***** Page 1
  "2019-12-11" => Collection {#516 ▶}
  "2019-12-10" => Collection {#518 ▶}
  "2019-12-09" => Collection {#555 ▶}

****Page 2  
"2019-11-16" => Collection {#554 ▶}
  "2019-11-15" => Collection {#553 ▶}
  "2019-11-14" => Collection {#556 ▶}

  **** Page 3
"2019-11-13" => Collection {#551 ▶}
  "2019-11-12" => Collection {#550 ▶}
  "2019-06-15" => Collection {#552 ▶}
TheRealHyveMind's avatar

Use the ->paginate() method instead of the ->get() I believe.

https://laravel.com/docs/6.x/pagination

If you're trying to set ranges for each page, so it's not just a number of records, but any number of records within a given range for each page, I would suspect you'd need to do that as seperate queries. I don't think you'd be able to do that with the usual pagination.

Sinnbeck's avatar

You will need to create a custom paginator as the normal one gets the first x records

Please or to participate in this conversation.