Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Collection macro for invoking methods on (nested) items
<?php
use Illuminate\Support\Collection;
/**
* Invoke the method each (nested) item of the collection, returning the result of each invoked method.
*
* @var string $method The method or the path of the method separated with @.
* @var mixed $arguments,... Any optional arguments to pass to the invoked method.
* @return static
*/
Collection::macro('invoke', function ($method, ...$arguments) {
$segments = explode('@', $method);
if (count($segments) == 2) {
$path = $segments[0];
$method = $segments[1];
return $this->pluck($path)->invoke($method, ...$arguments)->collapse();
}
return $this->map(function ($item) use ($method, $arguments) {
return call_user_func([$item, $method], ...$arguments);
})
});
// Before
$friends->map(function ($friend) use ($location) {
return $friend->isNear($location);
});
// After
$friends->invoke('isNear', $location);
// Before
$friends->map(function ($friend) use ($location) {
return $friend->location->getDistanceFrom($location);
});
// After
$friends->invoke('location@getDistanceFrom', $location);
@sebdesign

This comment has been minimized.

Copy link
Owner Author

@sebdesign sebdesign commented Nov 7, 2016

Inspired from lodash's invokeMap.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment