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

Laravel Developer
San Jose, CA
X3 Builders
Lead Front End Developer
Remote
continued
Full-Stack Laravel Developer
Cologne
Revive Interior
Intermediate PHP Developer (Full Stack | CakePHP | Laravel | Vue | jQuery)
Remote
continued
Senior PHP Developer (Full Stack | CakePHP | Laravel | Vue | jQuery)
Remote
continued
Laravel Developer
Amsterdam (partially remote possible)
Let's Book
Web Developer (Laravel)
Tweed Heads, New South Wales, AUSTRALIA
Tursa Employment & Training