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

StackBoot's avatar

Group by data in x number of days

Given I have the following query :

```    $data = FormSubmission::where('organization_id', session('organization_id'))
        ->select(DB::raw('DATE(created_at) as date'), DB::raw('count(*) as fs'))
        ->groupBy('date')
        ->get()->pluck('fs');  ```

Any idea on how to group by 4 days, meaning group by: 4 days ago 8 , 12 days ago.... ?

0 likes
8 replies
tykus's avatar

This should work - you can assign $numDays outside the query to group to the required number of days:

$data = FormSubmission::where('organization_id', session('organization_id'))
        ->selectRaw("
            COUNT(*) as fs, floor(datediff(now(), `date`) / $numDays) AS interval
        ")->groupBy('interval')
        ->pluck('fs');

You are calculating the interval based on the difference between the current date and each record's date field.

Lastly, the query builder has its own pluck method - avoids the need to use the Collection's pluck method.

biishmar's avatar
$data = FormSubmission::where('organization_id', session('organization_id'))
        ->get();

$data = $data ->groupBy(function ($item, $key) {
    return $item->created_at->diffForHumans();
});

$dataCount = $data->map(function($item) {
    return $item->count();
});

dd($data, $dataCount);
tykus's avatar

@biishmar that solution will group by a few seconds ago, 1 minute ago and so on; not what the OP asked for. In addition, you are getting PHP to do a lot of work that the database is more than capable of doing.

biishmar's avatar

@tykus like u said database is capable but php functions is more fast than database...

biishmar's avatar

@tykus nope, i tested it, i usually do like this get the data from database and manipulate it.. its just 0.00millisecond different not much

tykus's avatar

Tested with what, 10 records? What about 50, or 100, or 1000, or 10000, or 100000 records, are php functions is more fast than database in that case? What about memory?

StackBoot's avatar

@biishmar no mate that is not the way to go, my database has over 2 milion records ! And if you say that php its faster than mysql, you should be joking with us. Raw queries and caching are not helping much, imagine doing that on php!

Please or to participate in this conversation.