Simplifying Code with Laravel Collections

Mahadi Hassan
3 min readNov 3, 2023

--

In this article, we will examine Laravel collections, revealing their capacity to enhance the structure and efficiency of your code

Creating a Laravel Collection
Laravel provides three convenient methods for creating a collection

My personal preference leans towards using the collect() helper function due to its space-saving benefits in code samples.

Let’s kick things off with an example drawn from my experience at Shopify.

The Challenge

Imagine you have a JSON feed of products from a store, and you aim to calculate the total cost of purchasing all variants of Wallets and Lamp available in the store.

JSON Feed Example:

Let’s begin by retrieving the products from the JSON and creating a collection:

Imperative Approach:
The traditional way to calculate the total cost involves loops and conditionals. We can streamline this code using Laravel collections.

Our objective is to break down this extensive foreach loop into a series of independent, straightforward steps.

The first noticeable aspect is this if statement. We’re looping through all products, but we only perform any work if the product is a lamp or a wallet.

Let’s replace the conditional with a more elegant solution:

Now that we have all the product variants in a single collection, we can utilize the “map” method to extract their prices and eliminate both foreach loops:

At this point, we can condense the entire process into a single pipeline:

This is now a significantly more elegant solution, simplifying our code effectively.

--

--