Level 104
Use whereHas:
$sales = Sales::whereHas('product', function ($query) use ($term) {
$query->where('name', 'like', "%$term%");
}])->get();
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
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!
Use whereHas:
$sales = Sales::whereHas('product', function ($query) use ($term) {
$query->where('name', 'like', "%$term%");
}])->get();
Please or to participate in this conversation.