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

geetpurwar's avatar

Aggregating Query

Hi,

I have a mysql subscribers table and I wanted to pull aggregate hourly data. Can anyone help with Query Builder or Eloquent.

Example:

Hour 1 : 10 Subscribers Hour 2 : 10 (previous) + 5 (new) = 15 subscribers Hour 3 : 15 (previous) + 10 (new) =. 25 subscribers

Output could be:

[08:00:00 => 10, 09:00:00 => 15, 10:00:00 => 25
0 likes
1 reply
automica's avatar

Use something like the following to get your previous hours count

$result = [
Model::whereBetween(‘created_at’, now()->subHours(3), now()->subHours(2))->count(),
Model::whereBetween(‘created_at’, now()->subHours(2), now()->subHours(1))->count(),
Model::whereBetween(‘created_at’, now()->subHours(1), now())->count()
];

Shows results split by hour for last 3 hours

Please or to participate in this conversation.