Do your grouping in the query rather than in PHP:
DB::table('projects')
->selectRaw('id, DATE_FORMAT(created_at, "%Y%M%d%H") as hour, count(id) as number')
->groupBy('hour')
->get();
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
I want to count for example number of created projects for every hour. Is this possible to do with a db query. It's easily done in a loop after a query like
$res = DB::table('projects')
->select('id', 'created_at')
->get()->groupBy(function($date) {
return Carbon::parse($date->created_at)->format('Y-m-d H');
});
foreach ($res as $index => $row) {
$res[$index] = $row->count();
}
but that is not as clean and fast as a query would be. The result should be something like
[
"2017-11-20 08" => 2
"2017-11-20 09" => 2
"2017-11-20 11" => 1
"2017-11-20 12" => 5
"2017-11-20 13" => 3
"2017-11-20 19" => 2
]
Thanks!
Sorry... :facepalm: Of course you don't need the id at all... remove that from the SELECT and GROUP BY clauses:
DB::table('projects')
->selectRaw('DATE_FORMAT(created_at, "%Y%m%d%H") as hour, count(id) as number')
->groupBy('hour')
->get();
Please or to participate in this conversation.