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

vladshoob's avatar

Query: search products where subproducts has a value

Hello everyone, hope for little hint how to do next.

I have $products and related $subproducts, relationship (product has many subproducts) is in place.

What is correct way to find products where subproducts has some value.

$value = '00-100';
$products = Product::join('subproducts', 'products.id', '=', 'subproducts.product_id')
                ->where(('subproducts.article_code', 'like', "%$value%");

The problem is that the correct value is found. But I loose all my with relations in process of this query. Let me explain: product has 10 subproducts, I make described query, and then I don't have access to $product->subproducts.

Thanks in advance.

0 likes
3 replies
RamjithAp's avatar

Try this

$Product = Product::find(1);

$Product->subproducts()->where('article_code','LIKE', "%$value%")->get();
vladshoob's avatar

@RamjithAp

this way I will find only subproducts, but I need to return $products eloquent collection.

vladshoob's avatar

I think I found solution.

$value = '00-100';
$products = Product::join('subproducts', 'products.id', '=', 'subproducts.product_id')
                ->where(('subproducts.article_code', 'like', "%$value%")
        ->select('products.*');

Please or to participate in this conversation.