Laravel collection using map and contains

Laravel collection using map and contains

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

Stefan Bogdanescu

Founder & Senior Architect

The Closure Scope Issue in Laravel Collections

When working with Laravel collections, it is easy to assume that variables passed into closures are always accessible via use. However, the behavior of the contains method specifically can trip up developers who expect standard closure scoping rules to apply universally. In your specific case, you are trying to determine if a product ID exists within an unavailability list, but the logic fails because of how the contains method handles its closure arguments.

The core issue lies in the signature and behavior of the contains method when used as a callback. While standard PHP closures allow you to capture variables from the outer scope using use, Laravel's Collection::contains (and its alias whereIn) expects the closure to receive specific arguments: $value and $key. These represent the current item being iterated over within the collection and its corresponding key index, respectively.

In your code snippet, you are attempting to access $product inside the closure passed to contains:

'unavailableProducts'->contains(function ($value, $key) use ($product) {
    // ...
})

This syntax is technically valid PHP for defining a closure that uses an outer variable. However, there is a subtle but critical distinction in how Laravel processes the closure arguments versus the use variables. If the closure logic relies on $product, you must ensure that the scope is correctly captured. But looking closer at your specific comparison logic:

if ($value->product_id == $product->id) { ... }

The real problem isn't necessarily the use clause itself, but rather how the method contains evaluates the truthiness of the closure. The contains method returns true if the callback returns a "truthy" value for any item. Your logic returns false only when an ID match is found, and true otherwise. Consequently, if any item in $unavailableProducts does not match the current product, contains will return true. This means your available flag becomes true even if a match was found earlier in the loop, simply because subsequent items don't match.

The standard expectation with contains is that it acts as an existential check: "Does there exist at least one item that satisfies this condition?" When you invert the logic to return false on a match and true otherwise, you are effectively asking "Is there at least one non-matching item?", which almost always returns true unless every single item matches.

To fix this, you should utilize the negation of the check or switch to a method designed for checking existence directly. The most efficient approach is to use contains with a predicate that explicitly checks for the presence of the product ID without inverting the logic inside the closure. Alternatively, using every might be more semantically aligned if you want to verify that no unavailable products match the current one.

Here is a corrected pattern using every:

$allProducts = $products->map(function ($product) use ($unavailableProducts) {
    return [
        'id'            => $product->id,
        'title'         => $product->title,
        'available'     => $unavailableProducts['result']->every(function ($item) use ($product) {
            // Returns true if the current unavailable item DOES NOT match the product
            return $item->product_id != $product->id;
        }),
    ];
});

In this version, every returns true only if all items in $unavailableProducts['result'] satisfy the condition (i.e., none of them have an ID matching $product). This aligns perfectly with the definition of "available." If even one item matches, every returns false, correctly marking the product as unavailable.

If you prefer to stick with contains, you must ensure your predicate defines a positive match and then negate the result:

$allProducts = $products->map(function ($product) use ($unavailableProducts) {
    return [
        'id'            => $product->id,
        'title'         => $product->title,
        'available'     => !$unavailableProducts['result']->contains(function ($item) use ($product) {
            return $item->product_id == $product->id;
        }),
    ];
});

Here, contains finds the first match and returns true. The negation operator ! flips it to false, indicating the product is not available. This is often more readable because it mirrors natural language: "Is there an unavailable product with this ID?" followed by "Not available."

When dealing with large datasets, be mindful of performance implications. If $unavailableProducts['result'] is a massive collection, calling contains (or every) inside a map loop creates an O(n²) complexity scenario if not optimized. In production scenarios involving thousands of products, consider converting the unavailability list to an associative array keyed by ID using pluck before the mapping loop:

$unavailableIds = collect($unavailableProducts['result'])->pluck('product_id')->toArray();

$allProducts = $products->map(function ($product) use ($unavailableIds) {
    return [
        'id'            => $product->id,
        'title'         => $product->title,
        'available'     => !in_array($product->id, $unavailableIds),
    ];
});

This reduces the complexity to O(n) by utilizing native array lookups, ensuring your application remains responsive even as data volumes grow.

Our network