Laravel Eloquent Group By created_at only date and get Total

If you are looking to group by your query results by created_at column and get the total count of records created on each date. Here is how you can achieve that.

Consider you have a posts table and you are looking to fire a query which gives results of how many posts are created on particular date. created_at column contains the timestamp at which the particular row is created in the database table.

So if you use the Eloquent’s groupBy method in the query it will have exactly one record for each of the created_at timestamp.

And unfortunately eloquent’s groupBy doesn’t allow passing a closure function to modify the column format.

Here is how you can do it using Laravel Collection groupBy method

$posts = Post::orderBy('created_at')->get()->groupBy(function($item) {
     return $item->created_at->format('Y-m-d');
});

Once you get the results you can get the total count for each day by looping over the results


foreach($posts as $key => $post){
    $day = $key;
    $totalCount = $post->count();
}

Related Articles

If you like our content, please consider buying me a coffee.

Thank you for your support!

Buy me a coffeeBuy me a coffee

Leave a reply:

Your email address will not be published.

Site Footer