Use groupBy on Collections with Custom Callback Function

If you want to group result by some condition which isn’t a direct column in your database, you can do that by providing a closure function.

For example, if you want to group users by day of registration, here’s the code:

1$users = User::all()->groupBy(function($item) {
2 return $item->created_at->format('Y-m-d');
3});

⚠️ Notice: it is done on a Collection class, so performed AFTER the results are fetched from the database.

Like our articles?

Become a Premium Member for $129/year or $29/month
What else you will get:
  • 22 courses (477 lessons, total 38 h 20 min)
  • 2 long-form tutorials (one new every week)
  • access to project repositories
  • access to private Discord