Laravel 5.4 – Higher Order Messaging for Collections

Laravel 5.4 – Higher Order Messaging for Collections

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.


Filed in: Laravel 5.4 / Collections


Newsletter

Join the weekly newsletter and never miss out on new tips, tutorials, and more.

Laravel News Partners

Laravel Jobs

Full-Stack Developer
Tampa
Nu Image Medical
Senior Software Developer
Remote (US ONLY)/Kenilworth, NJ
Diversified
Senior Back-end Laravel API Developer - Immediate Contract (Full Time)
Remote
ApproveMe // Document Signing
Web Development Project Manager
Houston, TX
Swyft Filings
Experienced Laravel/VueJS Developer (Freelance)
Remote (preferably in the US)
Prosperly LLC
Senior React / Laravel Developer
Remote
The C.A.S.E. Engineering Group
Software Engineer
Boston
ButcherBox