In Laravel, you can use the groupBy and groupByDesc methods in combination with the date function to group a collection by day, month, and year. Here’s an example of how to do this:
$posts = Post::all(); // Assuming we have a Post model
$groupedPosts = $posts->groupBy(function ($post) {
return $post->created_at->format('Y-m-d');
});
the above code, we use the groupBy method and pass a callback function that formats the created_at date using the format method. The Y-m-d format represents the year, month, and day of the date. This callback function ensures that items with the same date are grouped together.
The resulting $groupedPosts variable will contain a new collection where each key represents a unique date, and the corresponding value is a collection of posts created on that date.
Accessing Grouped Data: Once we have our grouped collection, we can easily access and iterate over the grouped data. We can use the foreach loop to loop through each group and its corresponding items.
Here’s an example of how we can access the grouped data:
foreach ($groupedPosts as $date => $posts) {
echo "Date: " . $date . "\n";
foreach ($posts as $post) {
echo "- " . $post->title . "\n";
}
echo "\n";
}
[…] How to Group a Collection by Day, Month, and Year in Laravel ? […]