Laravel's Global Scopes are a type of Query Scopes. It allows you to create query constraints that are automatically applied to all model queries. This is useful for maintaining consistency in filtering, such as fetching only active records or using tenant-based filtering.
Global Scopes were created to enforce query constraints in a reusable way. This fits with Laravel's goal of reducing repetitive code.
Create a global scope:
php artisan make:scope ActiveScope
In the ActiveScope
class:
namespace App\Scopes;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Scope;
class ActiveScope implements Scope
{
public function apply(Builder $builder, Model $model)
{
$builder->where('status', 'active');
}
}
Apply the scope in your model:
protected static function booted()
{
static::addGlobalScope(new ActiveScope);
}
To disable the scope temporarily:
Post::withoutGlobalScope(ActiveScope::class)->get();