You can use whereHas for that.
Book::whereHas('tags', fn($q) => $q->where('id', $id))->get();
https://laravel.com/docs/8.x/eloquent-relationships#querying-relationship-existence
As you already suggested you can wrap that inside a local scope.
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
lets say, Book Model has Many-to-Many relationship with Tag model
Lets assume, there are 5 tags, of ID 1,2,3,4,5
Now I want to find the books, which is related to tag ID 3.
What currently I am doing:
$id = 3;
$related_books = [];
$all_books = Book::all();
foreach($all_books as $book) {
if($book->tags->pluck('id')->contains($id)) {
array_push($related_books, $book)
}
}
But this is inefficient, to search in all books. I am confused how can I build a query builder for this issue, to find like Book::containsTag(3)->get(). So I am asking for your help guys.
You can use whereHas for that.
Book::whereHas('tags', fn($q) => $q->where('id', $id))->get();
https://laravel.com/docs/8.x/eloquent-relationships#querying-relationship-existence
As you already suggested you can wrap that inside a local scope.
Please or to participate in this conversation.