Wednesday, March 8, 2017

How to access items within a collection map without breaking a fluent chain?

If you have a simple map using the Laravel collection, you can easily access the base collection by doing the following:

$items = [ "dog", "cat", "unicorn" ];
collect($items)->map(function($item) use ($items) {
    d($items); // Correctly outputs $items array
});

If using a fluent chain with filters / rejections, $items no longer represents the set of items:

$items = [ "dog", "cat", "unicorn" ];
collect($items)
    ->reject(function($item) {
        // Reject cats, because they are most likely evil
        return $item == 'cat'; 
    })->map(function($item) use ($items) {
        // Incorrectly (and obviously) outputs $items array (including "cat");
        d($items); 
    });

Question

Is it possible to access either the modified items array, or alternatively, get access to the collection in its current state.

Similar libraries in Javascript, like lodash, pass in the collection as the third argument - the Laravel collection does not.



via Chris

Advertisement