Add reusable query constraints with local scopes and automatic global scopes on Eloquent models.
Eloquent Scopes
class Post extends Model {
// Local scope
public function scopePublished(Builder $query): void {
$query->where("is_draft", false)
->where("published_at", "<=", now());
}
public function scopePopular(Builder $query, int $min = 100): void {
$query->where("views", ">=", $min);
}
// Global scope (applied to ALL queries)
protected static function booted(): void {
static::addGlobalScope("published", function (Builder $builder) {
$builder->where("is_draft", false);
});
}
}
// Usage
Post::published()->get();
Post::popular(500)->latest()->get();
Post::published()->popular()->paginate(10);
// Remove global scope for one query
Post::withoutGlobalScope("published")->get();