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();
}
Comments