How to set up an Anonymous Global Scopes in Laravel?

Asked

Viewed 125 times

2

Inside my model I’m using a Anonymous Global Scopes to miss some operations:

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

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

But I’m having a doubt, in the closure above the value 'Owner' was put in place of an argument called Scope, in my case Owner is:

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

My doubt is, what indeed must be present in this field set to Scope?

  • Which version of Laravel and could put the two classes?

1 answer

4


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

Browser other questions tagged

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