Evis
Evis

Reputation: 561

How to create scope in Laravel 5.4 on *belongsToMany* table connection?

The table scructure looks like this:

person
   id - integer
   name - string

company
   id - integer
   name - string

person_company
   person_id - integer
   company_id - integer

Here is the models:

class Person extends Model
{
    public function companies()
    {
        return $this->belongsToMany('App\Company', 'person_company');
    }
}

class Company extends Model
{
    public function persons()
    {
        return $this->belongsToMany('App\Person', 'person_company');
    }
}

Which means, one person can be part of multiple companies and each company can have many persons;

On the standard Laravel users table, we have:

users
   id - integer
   name - string
   company_id - integer

Where each user belogs to a company.


[PROBLEM 1]

How to create a scope to only bring the persons that belong to an specific company?

I tried to use GlobalScope:

class CompanyScope implements Scope
{
    public function apply(Builder $builder, Model $model)
    {
        $model->companies()->where('company_id', 1);
    }
}

class CompanyScope implements Scope
{
    public function apply(Builder $builder, Model $model)
    {
        $query->companies()->where('company_id', 1);
    }
}

But couldn´t get it through... I also tried LocalScopes:

public function scopeCo($query, $company_id)
{
    return $query->companies()->where('company_id', $company_id);
}

No success...


[PROBLEM 2]

Another thing to point out is the option to send a variable to the scope as of the local scope sample code above, where receive the company_id ($company_id) from user through the controller, using Auth::user()->company_id;.

What I expect to use on the controller was that my Local Scope would return the people linked to the users company, as of:

Person::Co(Auth::user()->company_id)->get();

Has anyone implemented this kind of scope, yet?

Thanks!

Upvotes: 2

Views: 2012

Answers (1)

Chay22
Chay22

Reputation: 2894

You can use whereHas to query the related table.

public function scopeCo($query, $company_id)
{
    $query->whereHas('companies', function ($query) use ($company_id) {
        $query->where('person_company.company_id', $company_id);
    });
}

Person::Co(Auth::user()->company_id)->get();

Upvotes: 3

Related Questions