Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

kova's avatar
Level 4

Query builder, return where all in

I will try one more time with this question, but now in new discussion instead of using already opened question. So, I have tables customers, products and customer_products. In customer_products there are id, customer_id and product_id columns. In search form I have 'products' input field, and can add multiple products for searching. So, in that case $request->products is array, and I want to pass that array in query builder to return all customers who bought at least all products from $request->products array. If each customers had only one products I would then use whereIn method, but when customers has multiple products ordered I dont have idea how to solve that. I tried with foreach but did not get the result I want. Anybody has idea how to solve this?

0 likes
2 replies
Snapey's avatar
Snapey
Best Answer
Level 122

you perhaps need to use whereHas on the Customer and then loop over each product using the wherehas for each id so that you end up with an AND condition between each of the wherehas

1 like
kova's avatar
Level 4

I got what I want with this code(whole query is big so I wrote only part with pivot table)

foreach($products as $product)
            {
                $customers->whereHas('products', function($query) use ($product) {
                    $query->where('product_id', $product);
                });
            }

Tnx @Snapey

Please or to participate in this conversation.