Rediska's avatar

How to filter the result of a collection?

Hi all! I received a collection of products that contains many-to-many relationships. The question is how to select only those products from this collection that match my request. For example, only those who have id color 1 or 2, id brand 1?

dd($products);

Illuminate\Database\Eloquent\Collection {#1843 ▼
  #items: array:7 [▼
    0 => App\Models\Product {#1652 ▼
      #fillable: array:17 [▶]
      ...
      #attributes: array:20 [▶]
      ...
      #relations: array:9 [▼
        "brands" => Illuminate\Database\Eloquent\Collection {#1734 ▼
          #items: array:1 [▼
            0 => App\Models\Brand {#1751 ▼
              ...
              #attributes: array:12 [▼
                "id" => 1
                "title" => "adidas"
                ...
              ]
            }
          ]
          "colors" => Illuminate\Database\Eloquent\Collection {#1734 ▼
          #items: array:2 [▼
            0 => App\Models\Color {#1751 ▼
              ...
              #attributes: array:12 [▼
                "id" => 1
                "title" => "red"
                ...
            1 => App\Models\Color {#1751 ▼
              ...
              #attributes: array:12 [▼
                "id" => 2
                "title" => "blue"
                ...
              ]
              ...
            }
          ]
      ...
        }
      ...
    }
    1 => App\Models\Product {#1651 ▶}
    2 => App\Models\Product {#1650 ▶}

I tried that, but it didn't work.

$filter = $products->
                whereIn('colors.id', ['1', '2'])
                ->whereIn('brands.id', ['1'])
                ->paginate('100');
$filter = $products
                ->filter(function ($query){
                    return $query->whereIn('brands.id', ['1']);
                })
                ->filter(function ($query){
                    return $query->whereIn('colors.id', ['1', '2']);
                })
                ->paginate('100');
0 likes
1 reply
jaseofspades88's avatar

You're confusing collections and query builder, I believe. The following should help:

$products->filter(fn (Product $product) => $product->color_id === 1);

You can introduce further conditions to the filter if necessary, in which case you might want to use a multi-line closure such as this..

$products->filter(function (Product $product) {
		return $product->id === 1; //whatever conditions can be added here
});

If this doesn't work, check the documentation: https://laravel.com/docs/10.x/collections#method-filter

3 likes

Please or to participate in this conversation.