Cross Join With Keys
Laravel ships with Arr::crossJoin
and $collection->crossJoin
helpers that generate the cartesian product (every combination) of each array. This is useful for building a single matrix from multiple arrays.
This is simple using the array method + spread operator but requires an extra step to use keys with collections.
Skip to the Collection macro section to get a snippet that allows you to cross join collections using keys.
Cross join assoc array (spread)
Using Collections
If we use a similar approach with collections we do not get the same output.
Oops, that’s not what we want.
Cross join without keys then map
In order to produce the same output as the original Arr::crossJoin
we could collection and cross join the array values and map the keys back in at the end.
or by using array combine...
This would work but depending on how your original data is coming in it could get a bit messy. Let’s create a collection macro to behave in a similar way to the array functions.
Collection macro
Add the following macro to a service provider. It merges any given items with the existing collection and spreads into the array cross join function.
This allows us to collect our builds using crossJoinWithKeys
or even without arguments...
and still receive the same output