The Global Scope is an appeal contained in Eloquent
to configure filters and restrictions for the Model
in all consultations SQL
that this model does. An example is logical deletion (Softdelete) which can be configured for any Model
of Eloquent
as described in the documentation.
When a Anonymous Global Scopes as an example contained in the documentation, a classe
or a closure
, and if it is configured with a closure
the first word is a text (that defines any name) and the second 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);
});
}
}
The code shows that in SQL
has a filter (Where
) that can only bring the ativos = 1
that is to say:
$clientes = Cliente::all();
to SQL
generated is
"select * from `clientes` where `ativo` = ?"
is a resource that can be explored where you do not want to type at all times a certain filter, but there is also the way to disable that is:
removing a:
$cliente = Cliente::withoutGlobalScope('ativo_filtro')->get();
removing several:
$cliente = Cliente::withoutGlobalScopes(['ativo_filtro', '', ...])->get();
and removing all:
$cliente = Cliente::withoutGlobalScopes()->get();
Which version of Laravel and could put the two classes?
– novic