Avoid nesting using the crossJoin and eachSpread collection functions original

by Freek Van der Herten – 1 minute read

While working on a package I found myself trying to combine some data. This is what my code looked like. Assume that $locales and $fields are arrays that are already populated.

collect($locales)->each(function (string $locale) {
    collect($fields)->each(function (Field $field) use ($locale) 
       $this->doSomeWork($locale, $field); 
    });
});

Sure, it's pretty already pretty clear, but there are also two cool collection methods that allow us to do the same thing. crossJoin creates a new collection with all possible combinations of the input given. eachSpread is a method that will pass each nested item as an argument to the callback.

Using those functions the code above can be rewritten as this:

collect($this->locales)
    ->crossJoin($this->originalFields)
    ->eachSpread(function (string $locale, Field $field) {
        $this->doSomeWork($locale, $field);
    });

Even though the first version of the code was pretty clear, I like this one better. There's no nesting involved here and we avoided the need for that damn use to import a variable.

Thanks Seb for this refactor!

Join 9,500+ smart developers

Every month I share what I learn from running Spatie, building Oh Dear, and maintaining 300+ open source packages. Practical takes on Laravel, PHP, and AI that you can actually use.

No spam. Unsubscribe anytime. You can also follow me on X.

Found something interesting to share? Submit a link to the community section.