How to group and count record by date using laravel?

Member

by jasen , in category: PHP Frameworks , a year ago

How to group and count record by date using laravel?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by gilbert , a year ago

@jasen 

You can group and count records by date in Laravel using the groupBy(), selectRaw() and count() methods. Here's an example:

1
2
3
4
5
6
7
8
$data = YourModel::selectRaw('DATE(created_at) as date')
                ->selectRaw('COUNT(*) as count')
                ->groupBy('date')
                ->get();

foreach ($data as $item) {
    echo $item->date . ': ' . $item->count . ' records';
}


In this example, YourModel is the model that you want to query. We are selecting the creation date of the records and counting them by date using the selectRaw() method. Then, we group the records by the date field and retrieve the result with the get() method.


Finally, we loop through the result and display the date and the count of records for each date.


You can adjust this example based on your specific requirements and model structure.

Related Threads:

How to group time column into 5 second intervals and count rows using presto?
How to display record count in laravel?
How to group by and count in laravel blade?
How to check current date record in laravel?
How to query from multiple tables and group them by date in laravel?
How to update multiple record using laravel?