Here’s a small tip you may have skimmed right past. Since Laravel 5.4, several methods of the Collection class come with “shortcuts” for performing common actions on their items. Let’s look at a few examples.
Say we have a User model and we want to run an operation on every result of a query. For example, sending each user a notification about the company rules… but only to the ones who haven’t been notified yet. To run an action on every user, we could reach for each().
Traditionally, you’d do this:
$users = User::where('notified', false)->get();
$users->each(function ($user) { $user->sendTermsNotifications();});But with higher order messages, you can shrink that down to this:
$users = User::where('notified', false)->get();
$users->each->sendTermsNotifications();A shorter syntax that does exactly the same thing. Let’s see another one.
Retired employees at our company get a $1,000 benefit. Assuming we already have a collection with every employee in memory ($employees), we’d probably skip the extra database query and filter that collection with filter() to keep only the retired ones, and then hand each of them the benefit. Something like this:
$employees->filter(function ($employee) { return $employee->is_retired;})->each(function ($retired) { $retired->getBenefit(1000);});We could squeeze it into this, though:
$employees->filter->is_retired->each->getBenefit(1000);Cool, right? 👌 One last example.
Say we want two collections: one with the moderators of our forum and one with everybody else. How would we get them out of our users collection? Well, one option is the partition() method:
list($moderators, $nonModerators) = $users->partition(function ($user) { return $user->is_moderator;});With what we learned today, you could cut it down to this:
list($moderators, $nonModerators) = $users->partition->is_moderator;These shortcuts work with the average, avg, contains, each, every, filter, first, flatMap, groupBy, keyBy, map, max, min, partition, reject, some, sortBy, sortByDesc, sum and unique methods.
Wrapping up
I used these methods on Eloquent query results here, but you can use them on any collection you like, for example collect(['this', 'is', 'my', 'cool', 'array']). Also, a few of these examples could be solved in an easier or more efficient way with a different method, but they do the job of showing the idea. Hope it comes in handy someday 🤘😉.