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

dgvai's avatar
Level 1

How to query by Eloquent ORM value?

Let's make it quick,

I have two models:

  • User
  • UserBalance

with a one-to-one relationship.

I can perform such relationship actions like:

UserBalance::find(1)->user->name;   // returns name

Now I want to perform a query, but now I am confused! What I want to do:


UserBalance::with(['user'])->where( ... )  // here I am confused

/**
*  What I wanna do: where()->user->isActive()   
*  note: isActive() is a public function on User model
*  which performs some other actions.
**/ 
0 likes
2 replies
Sinnbeck's avatar

With can take a function :)

UserBalance::with(['user' => function($query) {
    $query->where('active', 1); //or some other query on the users table
}])->get();

But most likely you are actually after whereHas (to filter UserBalance) As it is one to one, the with does not need any query :)

UserBalance::with('user')->whereHas('user', function($query) {
    $query->where('active', 1); //or some other query on the users table
})->get();
MichalOravec's avatar

You can also save closure to the variable, if it's same.

UserBalance::with(['user' => $closure = function($query) {
    $query->where('active', true);
}])->whereHas('user', $closure)->get();

Please or to participate in this conversation.