Simon Kollross

Simon Kollross

Software developer, blogger, elegant code enthusiast.

Working with Laravel collections

I like Laravel collections very much and I favour a functional approach towards solving list problems. So I’d like to start a series where I share tips about working with collections on upcoming problems in my current projects. Lately I wanted to transform the following structure

$vendors = [
    'FruitHouse' => ['Apples', 'Bananas', 'Cherries'],
    'EatFresh' => ['Apples', 'Bananas', 'Berries']

into this “inverted” one:

$vendorsByFruits = [
    'Apples' => ['FruitHouse', 'EatFresh'], 
    'Bananas' => ['FruitHouse', 'EatFresh'], 
    'Cherries' => ['FruitHouse'], 
    'Berries' => ['EatFresh']

My first approach was very traditional using a nested foreach loop:

$vendorsByFruits = [];
foreach ($vendors as $vendor => $fruits) {
    foreach ($fruits as $fruit) {
        $vendorsByFruits[$fruit][] = $vendor;

But I wanted to have this as a single collection transformation. So finally I came up with this solution:

$vendorsByFruits = collect($vendors)->map(function ($fruits, $vendor) {
    return ['vendor' => $vendor, 'fruits' => $fruits];
})->groupBy('fruits')->map(function ($group) {
    return $group->pluck('vendor');

I hope you’ll find this tip useful!