Higher Order Messages in Laravel
Aug 8, 2017 · 1 min read
Laravel Collection has recently supported the higher order messages. What this means, we can perform shortcuts on implementing methods that each objects has.
The collection methods that provide higher order messages are: average, avg, contains, each, every, filter, first, flatMap, map, partition, reject, sortBy, sortByDesc, and sum.
For example:
$responses = Response::whereIn('question_id', [4, 7, 12])->get();// For converting each item to array you would do something like this$responses = $responses->map(function($item)
return $item->getAttributes(); // toArray works as well
);// But it is much cleaner with Higher order messaging.
$responses = $responses->map->getAttributes();// What it does is it simply calls getAttributes methods in each item and maps the collection.
// You can chain as much as you want like$responses->reject->deleted_at->map->getAttributes();
Everything is awesome.

