Higher Order Messages in Laravel

Suman Shrestha
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.

laravelnepal

From laravel developers of nepal

Suman Shrestha

Written by

laravelnepal

From laravel developers of nepal

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade