How to create Scope in Laravel 5.4 with linked tables via belongsToMany

Asked

Viewed 158 times

0

The structure of the table is this:

pessoa
   id - integer
   nome - string

unidade
   id - integer
   nome - string

pessoa_unidade
   pessoa_id - integer
   unidade_id - integer

I have the models:

class Pessoa extends Model
{
    public function unidades()
    {
        return $this->belongsToMany('App\Unidade', 'pessoa_unidade');
    }
}

class Unidade extends Model
{
    public function pessoas()
    {
        return $this->belongsToMany('App\Pessoa', 'pessoa_unidade');
    }
}

That is, one person can participate in several units and one unit can have several people;

In the default users table of Laravel we have:

users
   id - integer
   nome - string
   unidade_id - integer

Where every user has his drive.

[PROBLEM 1]

How to create a Scope to seek only the linked persons of a given unit?

I tried using Globalscope:

class UnidadeScope implements Scope
{
    public function apply(Builder $builder, Model $model)
    {
        $model->unidades()->where('unidade_id', 1);
    }
}

class UnidadeScope implements Scope
{
    public function apply(Builder $builder, Model $model)
    {
        $query->unidades()->where('unidade_id', 1);
    }
}

But I couldn’t... I tried to use Localscopes:

public function scopeUn($query, $unidade)
{
    return $query->unidades()->where('unidade_id', $unidade);
}

Unsuccessful...


[PROBLEM 2]

Another point of this question is to have the option to send a variable to the scope as in the example I did above in local Scope where I send the unidade_id ($unit) of the user through the controller, using Auth::user()->unidade_id;.

The expectation was that in the controller, the Local Scope return all persons linked to the logged in user, as follows:

Pessoa::Un(Auth::user()->unidade_id)->get();

Has anyone ever managed to implement something like?

  • No need to ride scope for this or else did not understand your question, see when fetching the unit code 1 will already bring people linked by the many relationship to many, do not need to make a scope, but, if I did not understand well if could improve your question?

  • Great @Virgilionovic! Thanks for the return my friend! I know what can be done in the controller, bringing the unit of the user and from there bring people $unit = Unit::find(Auth::user()->unidade_id); and $unit->persons()->get(), but my idea is to keep the controller logic as clean and direct as possible, for example, in the function getPeople bring people People:(); and not having to always link the Unit, I think it would be ideal to use Scope in this case, just think, if I can I will try to implement so, if no, I will do via controller even. Thanks!

1 answer

0


Browser other questions tagged

You are not signed in. Login or sign up in order to post.