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();