Add count of duplicate values to Laravel collection

Add count of duplicate values to Laravel collection

  1. Blog
  2. 15 November 2026
  3. 3 min read

Stefan Bogdanescu

Founder & Senior Architect

Aggregating Cart Line Quantities by Article ID in Laravel Collections

When dealing with shopping cart logic or inventory aggregation, you often encounter scenarios where a collection contains multiple distinct line items that refer to the exact same product. In this specific case, we are working with a CartLine model collection where duplicates exist based on the article_id. The goal isn't to collapse these into a single row or remove the duplicates entirely; rather, the objective is to preserve the structure of the collection while updating the quantity property for each item. The logic requires summing the quantities of all items sharing the same article_id and reflecting that total back onto every instance of that ID within the collection.

This operation is a classic example of why understanding Laravel's collection methods beyond simple iteration is valuable. You are essentially performing a group-by aggregation but maintaining the original array shape, just with updated values. A naive approach might involve looping through the collection, storing sums in an associative array, and then rewriting the collection. While that works, it introduces unnecessary intermediate data structures and can be less efficient if the collection is large.

Laravel provides a more elegant solution using groupBy combined with map. This functional programming approach allows you to define the grouping logic and the transformation logic in a single, readable chain. The strategy involves grouping the collection by the key that defines duplication—in this case, article_id. Once grouped, you can iterate over the groups, calculate the sum of the quantity property for each group, and then map those sums back onto the original items within that group.

Here is how you can implement this using Laravel Collections:

$collection = $cart->lines; // Assuming $cart contains your CartLine collection

$aggregatedCollection = $collection->groupBy('article_id')->map(function ($group, $id) {
    // Calculate the total quantity for this specific article_id
    $totalQuantity = collect($group)->sum('quantity');

    return $group->map(function ($item) use ($totalQuantity) {
        // Create a new instance of CartLine to avoid mutating the original data directly
        // unless mutation is explicitly intended.
        return (new CartLine())
            ->setArticleId($item->getArticleId())
            ->setArticleName($item->getArticleName())
            ->setParentLineId($item->getParentLineId())
            ->setQuantity($totalQuantity);
    });
});

In this implementation, groupBy('article_id') returns a collection of collections, where the outer keys are the IDs and the inner collections hold all items matching that ID. The map closure then iterates over these groups. Inside the closure, we first calculate the sum. Then, we apply a second map to the specific group to iterate over every duplicate item. We reconstruct each item with the calculated $totalQuantity.

It is crucial to note that this approach creates new instances of CartLine objects rather than mutating the existing ones in memory. If your collection contains complex relationships or observers listening for property changes, direct mutation might trigger side effects you don't want. Using a fresh instance ensures data integrity. However, if performance is a concern and you are certain no other parts of your application hold references to these specific array objects, simple assignment ($item->quantity = $totalQuantity) inside the map is faster but riskier regarding shared state.

Another consideration is handling null values or edge cases where an article_id might be missing. The groupBy method handles keys naturally, but if your data relies on a specific index order for rendering (e.g., frontend pagination expects items in a specific sequence), note that groupBy does not preserve the original order of appearance within the groups, nor does it necessarily guarantee the order of the keys themselves unless you sort them afterward. If preserving the original insertion order is critical, you might need to sort the resulting collection by an original index stored alongside the data or reconstruct the order manually.

This pattern—grouping to calculate aggregates and then mapping back to the original structure—is highly reusable. Whether you are summing prices for tax calculations, counting occurrences of specific tags, or normalizing inventory counts from a batched import, this combination of groupBy and map offers a concise way to handle it without writing verbose loops.

Our network