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

dmag's avatar
Level 6

How to constrain a relationship by pivot's other relationship.

I have the following tables:

apartment: id, address
tenant: id, name
roles: id, name
apartment_tenant: apartment_id, tenant_id, role_id

and model

class Apartment extends Model
{
    public function tenants(): BelongsToMany
    {
        return $this->belongsToMany(Tenant::class);
    }
}

How can I get tenants that have name "admin" for a particular apartment?

0 likes
1 reply
LaryAI's avatar
Level 58

To get tenants that have the name "admin" for a particular apartment, you can use the wherePivot method in Laravel's Eloquent ORM. Here's an example of how you can modify the tenants method in the Apartment model:

class Apartment extends Model
{
    public function tenants(): BelongsToMany
    {
        return $this->belongsToMany(Tenant::class)
            ->wherePivot('role_id', function ($query) {
                $query->from('roles')->where('name', 'admin');
            });
    }
}

This code adds a constraint to the relationship query using the wherePivot method. It checks the role_id column in the pivot table (apartment_tenant) and filters the tenants based on the name column in the roles table.

Now, when you call the tenants relationship on an instance of the Apartment model, it will only return the tenants with the name "admin" for that particular apartment.

$apartment = Apartment::find(1);
$adminTenants = $apartment->tenants;

Note: Make sure to replace 1 with the actual ID of the apartment you want to retrieve the tenants for.

1 like

Please or to participate in this conversation.