What are higher order messages?
Higher order messages let you call collection methods using property-access syntax rather than writing a closure. You can retrieve a property or call a method on every element without any anonymous functions.$users->map->name means “map over each user and return its name property.”
How it works — HigherOrderCollectionProxy
When you access$collection->map as a property, the __get() method in the EnumeratesValues trait is called.
$proxies list, a HigherOrderCollectionProxy instance is returned. The proxy holds a reference to the collection and the method name.
Property access via __get
Accessing a property on the proxy (->name) triggers the proxy’s __get().
$users->map->name is equivalent to:
Method calls via __call
Calling a method on the proxy (->activate()) triggers the proxy’s __call().
$users->each->activate() is equivalent to:
Supported methods
The methods available as higher order messages are defined in the$proxies array.
Collection::proxy().
Practical use cases
Eloquent model collections
Higher order messages are especially useful with Eloquent collections.Filtering
Aggregation
Grouping and sorting
Flattening nested collections
Checking conditions
Higher order messages vs closures
Higher order messages are concise, but they do not cover every scenario.Adding custom methods to the proxy list
Register the method as a macro first, then proxy it.For string collections, the proxy’s
__call() attempts a static method call on the string. In practice, higher order messages work most naturally with Eloquent models or other objects.Next steps
The Conditionable trait
Learn how when() and unless() work internally, and how to use them in QueryBuilder and custom classes.