DEV Community

Kay Gosho
Kay Gosho

Posted on

How wonderful feature 'Higher Order Messages' in Laravel 5.4

I was moved to the feature "Higher Order Messages" in Laravel added at 5.4.

I would like to show some examples.


There are two models Company and User.

The obvious relationship is:

  • Company hasMany Users
  • User belongsTo Company

Company Model has these methods:

  • getIsContractExpiredAttribute
  • notifyContractExpiration

(This example has some problems but this is for just example)

Then we will take 5 contract expired companies randomly and send emails to those companies.

Before (~ 5.3)

    ->filter(function ($company) {
        return $company->isContractExpired;
    ->each(function ($user) {

Enter fullscreen mode Exit fullscreen mode

After (5.4 ~)

Enter fullscreen mode Exit fullscreen mode

There are less closure. Simple, great readability.


In the above example, Company::all()->map returns Illuminate\Support\HigherOrderCollectionProxy which has a lot of tasks.

The following methods support HigherOrderCollectionProxy.

  • average
  • avg
  • contains
  • each
  • every
  • filter
  • first
  • flatMap
  • map
  • partition
  • reject
  • sortBy
  • sortByDesc
  • sum

For example, Company::all()->sum->isContractExpired returns count of contract expired companies.

A lot of fun like SQL, right?

Top comments (0)