Sounds like you want to group by date?
->groupByRaw('DATE(created_at)')
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
I have a table of Forms where people can sign up and their details are stored in the table. I am trying to display the statistics on how many number of people sign up on the particular day. For instance, my blade view should look like this:
Date Number of Sign Up
25 Feb 2022 1
24 Feb 2022 2
23 Feb 2022 0
22 Feb 2022 0
21 Feb 2022 5
20 Feb 2022 0
19 Feb 2022 0
18 Feb 2022 0
TOTAL 8
It displays the current day up until 7 days before so it will be dynamic.
Now I have to write some complicated query for the data in my controller:
$sign_ups = DB::table('forms')
->select('created_at', DB::raw('count(*) as sign_ups'))
->whereBetween('created_at', [date('Y-m-d', strtotime('-7 days')), date('Y-m-d')])
->groupBy('created_at')
->get();
Or a more Eloquent-ish query:
$sign_ups = Form::whereBetween('created_at', [date('Y-m-d', strtotime('-7 days')), date('Y-m-d')])
->groupBy('created_at')
->orderBy('created_at', 'DESC')
->get(array(
DB::raw('Date(created_at) as date'),
DB::raw('COUNT(*) as "sign_ups"')
));
The only issue here it does not distinct from the day but the time as well so every count returns as 1.
1st element
"date" => "2022-02-24"
"sign_ups" => 1
2nd element
"date" => "2022-02-24"
"sign_ups" => 1
3rd element
"date" => "2022-02-23"
"sign_ups" => 1
........
Another issue is that some days do not have any record so how would I populate it on the blade without record. How do I go about tackling this issue?
@CookieMonster ah sorry I missed that. The same
$sign_ups = DB::table('forms')
->select(DB::raw('DATE(created_at) as date'), DB::raw('count(*) as count'))
->whereBetween('created_at', [date('Y-m-d', strtotime('-7 days')), date('Y-m-d')])
->groupByRaw('DATE(created_at)')
->orderByRaw('DATE(created_at) desc')
->get();
Please or to participate in this conversation.