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

chimit's avatar

contains() for Query Builder

I have some relationships between models (One to Many and Many to Many) and I need to check whether one entity belongs to another:

if ($user->books->contains($book)) {
    // do something
}

This looks clean and readable and also it supports any kind of relationships. But there is a small problem with performance because we need to grab all user's books Collection.

Query Builder is more efficient:

if ($user->books()->where('id', $book->id)->exists()) {
    // do something
}

Is there any way to combine simplicity of the first approach and efficiency of the second? Something like:

if ($user->books()->contains($book)) {
    // do something
}
0 likes
1 reply
Snapey's avatar

Maybe with a macro? But it would be same code, just with a little complexity hidden

Please or to participate in this conversation.