Posts Learn Components new Snippets new Categories Tags About Device Beast sponsor
/

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

19 views

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.

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

Snippets by

PostSrc poster

PostSrc

Full stack developer mainly focusing on the front end side of the web. The main author of PostSrc and loves writing tutorial and guides online.

new

PostSrc Code Components

Collection of Tailwind CSS components for everyone to use. Browse all of the components that are right for your project.

View Components

Other Code Snippets

More