To achieve this you can make use of the "custom callback function" available to the "groupBy" method and below is how you can implement it.
Post::orderByDesc('published_at') ->get(['title', 'published_at']) ->groupBy(function ($item, $key) { return $item->published_at->format('m-d'); });
The "groupBy" function accepts a closure and you can access the "item" as well as the index "key" as the first and second argument.
Do note that for the criteria to group the result is by the "month" and "date" but depending on your use case you can specify this however you prefer it to be.
$item->published_at->format('m-d');
The return example for the condition above will look like below.
[ "06-28" => Illuminate\Database\Eloquent\Collection {#1466 all: [ App\Models\Snippet {#2396 title: "Set TailwindCSS Utilities Important", published_at: "2021-06-28 20:50:00", }, App\Models\Snippet {#2397 title: "How to Enable TailwindCSS JIT Compiler", published_at: "2021-06-28 20:00:00", }, App\Models\Snippet {#2398 title: "Conditionally Include Partial Views in Laravel Blade", published_at: "2021-06-28 19:00:00", }, ], }, "06-27" => Illuminate\Database\Eloquent\Collection {#2393 all: [ App\Models\Snippet {#2399 title: "How to Rename the master branch to main in Git", published_at: "2021-06-27 20:30:00", }, App\Models\Snippet {#2400 title: "How to Install Laravel in the Current Directory", published_at: "2021-06-27 19:00:00", }, App\Models\Snippet {#2401 title: "Caching Queries and Values in Laravel 8", published_at: "2021-06-27 13:00:00", }, App\Models\Snippet {#2402 title: "How to Cache Route and Cache Config in Laravel 8", published_at: "2021-06-27 10:00:00", }, ], } ]
Leave a reply