How wonderful feature 'Higher Order Messages' in Laravel 5.4

acro5piano

Kay Gosho

Posted on February 18, 2018

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.

https://laravel.com/docs/5.5/collections#method-flatmap

I would like to show some examples.

Prerequisite

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)

Company::with('users')
    ->all()
    ->filter(function ($company) {
        return $company->isContractExpired;
    })
    ->take(5)
    ->pluck('users')->flatten()
    ->each(function ($user) {
        $user->notifyContractExpiration;
    });


Enter fullscreen mode Exit fullscreen mode

After (5.4 ~)

Company::with('users')
    ->all()
    ->filter->isContractExpired
    ->take(5)
    ->flatMap->users
    ->each->notifyContractExpiration;
Enter fullscreen mode Exit fullscreen mode

There are less closure. Simple, great readability.

Detail

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?

💖 💪 🙅 🚩
acro5piano
Kay Gosho

Posted on February 18, 2018

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related