How to group and count record by date using laravel?

Member

by jasen , in category: PHP Frameworks , 6 months ago

How to group and count record by date using laravel?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by gilbert , 6 months 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.