PHP
Implement Application-Wide Filters with Eloquent Global Scopes
Discover how to apply universal constraints to all queries of a specific Eloquent model using global scopes, perfect for multi-tenancy or status filtering.
// app/Models/Post.php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use App\Scopes\ActiveScope; // Custom scope class
class Post extends Model
{
protected static function booted(): void
{
static::addGlobalScope(new ActiveScope);
}
// To temporarily remove the global scope for a query:
// Post::withoutGlobalScope(ActiveScope::class)->get();
// Post::withoutGlobalScopes()->get(); // Removes all global scopes
}
// app/Scopes/ActiveScope.php
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): void
{
$builder->where('is_active', true);
}
}
How it works: Eloquent global scopes apply constraints to all queries for a given model. This is ideal for ensuring certain conditions (like `is_active = true` or multi-tenancy `tenant_id = X`) are always met unless explicitly removed. You define a scope class implementing `Illuminate\Database\Eloquent\Scope` and apply it in the model's `booted` method using `static::addGlobalScope()`.