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

alchermd's avatar

How do I query for a field of an Eloquent model's relationship?

So when a Member buys a Product, a Sales object is saved into the database. It contains the member_id and the product_id among other fields. Now, I'd like to implement a search field in which the user can search through the Sales product name.

public function index(Request $request)
{
        $term = $request->query('term');

        $sales = /** Find all Sales objects in which its Product contains the $term variable. */;

        return $sales;
}

How do I create that query? My searching led me to this snippet:

$sales = Sales::with(['product' => function ($query) use ($term) {
            $query->where('name', 'like', "%$term%");
}])->get();

But it still loads all of the Sales -- it just sets the relationship to product as null for those that don't contain the $term.

Any help is appreciated!

0 likes
2 replies
tykus's avatar
tykus
Best Answer
Level 104

Use whereHas:

$sales = Sales::whereHas('product', function ($query) use ($term) {
            $query->where('name', 'like', "%$term%");
}])->get();
alchermd's avatar

Oh wow. That's painfully simple lol. I'm probably looking at the wrong side of the docs. Thanks!

Please or to participate in this conversation.