Laravel 5.4 – Higher Order Messaging for Collections
Published on by Eric L. Barnes
Development for Laravel 5.4 is now underway and new features are being leaked out as they are merged in. One new feature announced is “higher order” messages for Collections that was contributed by @franzliedke.
The best way of showcasing this new feature is through code samples. Pretend you have a collection and you want to perform an operation on each of the items:
$invoices->each(function($invoice) { $invoice->pay();});
With this new feature you will be able to simplify this into:
$invoices->each->pay();
Another example demonstrated is taking this:
$employees->reject(function($employee) { return $employee->retired;})->each(function($employee){ $employee->sendPayment();});
Then, turning it into:
$employees->reject->retired->each->sendPayment();
Here is the commit to see how this was actually implemented and here is an article that inspired this feature.
Eric is the creator of Laravel News and has been covering Laravel since 2012.