Home > OS >  laravel where condition for related eloquent
laravel where condition for related eloquent

Time:03-25

I have to Models User and UserAttr

User is like :

id name
1 john
2 doe

UserAttr is like

id user_id job
1 1 seller
2 2 teacher

them relation is :

for user :

    //User MODEL
    public function UserAttr(){
        return $this->hasOne(UserAttr::class);
    }

for UserAttr :

    //UserAttr MODEL
    public function UserAttr(){
             return $this->belongsTo(User::class);
    }

Inside of controller i want to return this

Return all Users Where They job is Seller

i try

$users = User::where(User::UserAttr()->where('job','teacher'));
return $users;

but it not works

CodePudding user response:

First, 'where' requires two arguments. where('column', 'value'). Second, until you use a function dedicated for returning the results, like find(1), first(), get(), you will always get a builder object.

In this particular case, you need to query the relationship. Something like this should work for you.

User::with('userAttr')->whereHas('userAttr', function($query){ 
   return $query->where('job', 'teacher');
})->get();

For reference: https://laravel.com/docs/9.x/eloquent-relationships#querying-relationship-existence

  • Related