Example 5-31. Adding a global scope using a closure
class Contact extends Model
{
protected static function boot()
{
parent::boot();
static::addGlobalScope('active', function (Builder $builder) {
$builder->where('active', true);
});
}
}
Example 5-32. Creating a global scope class
<?php
namespace App\Scopes;
use Illuminate\Database\Eloquent\Scope;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Builder;
class ActiveScope implements Scope {
public function apply(Builder $builder, Model $model) {
return $builder->where('active', true);
}
}
Example 5-33. Applying a class-based global scope
<?php
use App\Scopes\ActiveScope;
use Illuminate\Database\Eloquent\Model;
class Contact extends Model
{
protected static function boot()
{
parent::boot();
static::addGlobalScope(new ActiveScope);
}
}