DEV Community

Kay Gosho
Kay Gosho

Posted on

3 1

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?

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay