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; }); After (5.4 ~)
Company::with('users') ->all() ->filter->isContractExpired ->take(5) ->flatMap->users ->each->notifyContractExpiration; 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?
Top comments (0)