Sunnan's avatar

Apply Where condition on Relations in Laravel Eloquent

Hello, How can i add where condition on relation in laravel model e.g A Subscription model has a relation with User so my relation is

public function user(){ return $this->belongsTo(User::class , 'user_id' , 'id'); }

Now i want to add a where condition on Users table like i want to make a belongsTo relation with user where user_type = 10

Something like this public function user(){ return $this->belongsTo(User::class , 'user_id' , 'id')->where('user_type', 10); }

But its not working, is there any workaround for this ?

0 likes
1 reply
LaryAI's avatar
Level 58

To add a where condition on a relation in Laravel Eloquent, you can use the whereHas method. Here's an example of how to modify the user method in the Subscription model to add a where condition on the User model:

public function user()
{
    return $this->belongsTo(User::class, 'user_id', 'id')->where('user_type', 10);
}

Instead of using the belongsTo method, you can use the whereHas method to add a where condition on the related User model. Here's an example:

public function user()
{
    return $this->hasOne(User::class, 'id', 'user_id')->whereHas('userType', function ($query) {
        $query->where('user_type', 10);
    });
}

This will return only the User model that has a user_type of 10.

Please or to participate in this conversation.