Posts Learn Components Snippets Categories Tags Tools About

Grouping Collection With Custom Callback Function in Laravel

Learn how to group collection result with a custom callback function to specify the condition of the criteria

Created on Jun 29, 2021


Sometimes you might want to group the result that's returned by the Laravel collection but there's a certain condition that you want to define.

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.

  ->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.

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",

If you like our tutorial, do make sure to support us by being our Patreon or buy us some coffee ☕️