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

dgvai's avatar
Level 1

Can anybody help me to build its query builder?

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.

0 likes
2 replies
dgvai's avatar
Level 1

Shit, I forgot about whereHas, this instantly reminded me what to do.. Thank you so much!!

1 like

Please or to participate in this conversation.