How to configure an Anonymous Global Scopes in Laravel?

2

Within my model I'm using an Anonymous Global Scopes to skip some operations:

protected static function boot()
{
    parent::boot();

    static::addGlobalScope('owner', function (Builder $builder) {
        $builder->where('user_id', 1);
    });
}

But I have a question, in the above closure the 'owner' value was put in place of an argument called scope, in my case owner is:

public function owner()
{
    return $this->belongsTo(User::class);
}

My question is, what should actually be present in this field defined for scope?

    
asked by anonymous 06.02.2018 / 19:09

1 answer

4

Global Scope is a resource contained in Eloquent to configure filters and restrictions for Model in all queries SQL that this template does. An example is the logical exclusion ( SoftDelete) that can be configured for any Model of Eloquent as described in the documentation .

When setting up an Anonymous Global Scopes as an example contained in the documentation, a classe can be set up % or a% with%, and if it is set with a closure the first one is a text ( defining any name ) and the second is the anonymous function, example :

<?php namespace App\Models;

use Illuminate\Database\Eloquent\Builder;
use Illuminate\Foundation\Auth\User as Authenticatable;

class Cliente extends Authenticatable
{
    protected $table = 'clientes';
    protected $dates = ['created_at','updated_at'];
    protected $fillable = ['nome', 'sobrenome', 'email', 
                           'password', 'ativo'];
    protected $hidden = ['password'];
    public $timestamps = true;

    protected static function boot()
    {
        parent::boot();

        static::addGlobalScope('ativo_filtro', function (Builder $builder) {
            $builder->where('ativo',1);
        });
    }
} 

In the code it is shown that in closure has a filter ( SQL ) that can only bring Where ie:

$clientes = Cliente::all();

a ativos = 1 generated is

"select * from 'clientes' where 'ativo' = ?"

is a feature that can be exploited where you do not want to type a particular filter at all times, but there is also the way to disable it:

Removing one:

$cliente = Cliente::withoutGlobalScope('ativo_filtro')->get(); 

Removing multiple:

$cliente = Cliente::withoutGlobalScopes(['ativo_filtro', '', ...])->get(); 

and removing all:

$cliente = Cliente::withoutGlobalScopes()->get(); 
    
06.02.2018 / 19:45