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

bwrice's avatar
Level 11

Is it possible to create a local query scope that's dependent on an eloquent model relation?

I want to be able to do something like this:


//App\User

public function membershipType()
    {
        return $this->belongsTo(MembershipType::class);
    }

public function scopeMembershipTypeName($query, $membershipTypeName)
    {
        return $query->membershipType()->where('name', $membershipTypeName);
    }

This obviously doesn't work because "membershipType()" is not a method on the query builder. I'm curious if it's possible to create a query scope that for User's that is dependent on the membershipType relation. This way I can do a query like:

App\User::membershipTypeName('premium')->get();

Any help would be greatly appreciated. Thanks!

0 likes
1 reply
IgorBabko's avatar
Level 36

Hey -

public function membershipType()
{
    return $this->belongsTo(MembershipType::class);
}

public function scopeMembershipTypeName($query, $type)
    return $query->whereHas('membershipType', function ($query) use ($type) {
        $query->where('name', $type);
    });
}
1 like

Please or to participate in this conversation.