🔴 Laravel Intermediate

What are Global Scopes in Eloquent?

Answer

Global scopes add constraints to every query on a model automatically. The most common built-in global scope is the soft delete scope (automatically filtering out records where deleted_at is not null). Create a custom scope: implement Scope interface with an apply(Builder $builder, Model $model) method. Register in the model's booted() method: static::addGlobalScope(new ActiveScope). Or use an anonymous scope: static::addGlobalScope("active", fn($q) => $q->where("active", true)). Remove a global scope for a specific query: User::withoutGlobalScope(ActiveScope::class)->get(). Global scopes are useful for multi-tenancy (automatically filtering by tenant_id), data partitioning, and any constraint that should always apply to a model.