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

AyobamilayeY's avatar

Laravel query scope in related model.

Hello

I have Services that have a many-to-many relationship to People as contacts, connected by a services_contacts pivot table and I'm attempting to create a local scope query on the Service model to return the primaryContacts():

public function scopePrimaryContacts($query)
{
    $pivot = $this->contacts()->getTable();

    return $query->whereHas('contacts', function ($q) use ($pivot) {
        return $q->where("{$pivot}.is_primary", true);
    });
}

This returns the services, where I need it to return the people that are related as is_primary on the pivot table itself. I'd like to be able to call $this->primaryContacts on my Service model, like I can call $this->contacts to get any/all contacts. Any ideas where to go from here? Here are the relationships... contacts on the Service model:

public function contacts()
{
    return $this->belongsToMany(Person::class, 'services_contacts', 'service_uuid', 'person_uuid')
        ->withPivot('is_primary', 'is_active', 'contact_type_uuid')
        ->withTimestamps();
}

And services on the Person model:

public function services()
{
    return $this->belongsToMany(Service::class, 'services_contacts', 'person_uuid', 'service_uuid');
}

Thanks in advance.

0 likes
4 replies
tisuchi's avatar

@ayobamilayey

I have a question, do you really need to make its scope? Do you have any other thoughts about it? I am thought of something else.

1 like
tisuchi's avatar
tisuchi
Best Answer
Level 70

@ayobamilayey

I prefer to make a second relationship function by providing some additional conditions.

For example-

In your Service Model

public function primaryContact() 
{
    return $this->belongsToMany(Person::class, 'services_contacts', 'service_uuid', 'person_uuid')
            ->wherePivot('is_primary', true)
            ->wherePivot('is_active', true);
}
1 like

Please or to participate in this conversation.