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

kari's avatar
Level 1

Nested query using a relationship column

Hello guys, I have this default query

$products =  Product::with('category', 'skus');

after some conditions i am extending my query like this

$search = "SOMETHING"
$products->where(function ($q) use ($search) {
                $q->where("name", "like", "%$search%")
                    ->orWhere("price", "like", "%$search%");
                 //->orWhere("category.name", "like", "%$search%");
            });

but the last condition

->orWhere("category.name", "like", "%$search%");

doesnt work. How can I use relationship column in nested query :(

Thanx for any advice

0 likes
2 replies
staudenmeir's avatar
Level 24

Use whereHas():

->orWhereHas('category', function($query) use($search) {
    $query->where('name', 'like', "%$search%");
});
1 like

Please or to participate in this conversation.