Combining Collections with Laravel's crossJoin() method

Laravel devs, here's a gem for you: πŸ’Ž

The Laravel Collection class offers numerous methods to manipulate and combine data. One particularly powerful method is crossJoin(), which generates a Cartesian product of collections. This can be extremely useful for creating combinations from multiple data sets. Let's explore how to use the crossJoin() method with an example.

What is crossJoin()?

The crossJoin() method generates a Cartesian product of the collections passed as arguments. It returns a collection containing all possible combinations of the input collections. This is especially useful when you need to create combinations of data from different sets, such as products and their attributes, or dates and time slots.

Example: Generating Product Variations

Suppose you are building an e-commerce platform and you want to generate all possible variations of products based on their sizes and colors. Using crossJoin(), you can achieve this efficiently.

Step-by-Step Implementation

  1. Creating the Collections

Start by creating collections for the different attributes of the products:

$sizes = collect(['Small', 'Medium', 'Large']);
$colors = collect(['Red', 'Green', 'Blue']);
  1. Using the crossJoin() Method

Use the crossJoin() method to generate all possible combinations of sizes and colors:

$variations = $sizes->crossJoin($colors);

print_r($variations->all());
// Result: [
//     ['Small', 'Red'],
//     ['Small', 'Green'],
//     ['Small', 'Blue'],
//     ['Medium', 'Red'],
//     ['Medium', 'Green'],
//     ['Medium', 'Blue'],
//     ['Large', 'Red'],
//     ['Large', 'Green'],
//     ['Large', 'Blue']
// ]

In this example, the crossJoin() method generates all possible combinations of sizes and colors, resulting in a collection of product variations.

Conclusion

The crossJoin() method is a powerful addition to the Laravel Collection methods, enabling you to handle data combination tasks efficiently. Whether you are generating product variations, scheduling time slots, or combining multiple attributes, crossJoin() simplifies the process and keeps your code clean.

Found this helpful?

If this guide was helpful to you, subscribe to my daily newsletter and give me a follow on X/Twitter. It helps a lot!

Subscribe to Harris Raftopoulos

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
jamie@example.com
Subscribe