PHP
Reusable Query Filters with Local and Global Scopes in Laravel Eloquent
Simplify and reuse common query constraints across your Laravel application by defining powerful local and global Eloquent scopes for models.
// In App\Models\Post.php
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
// Local Scope: Can be called on the query builder
public function scopePublished($query)
{
return $query->where('is_published', true);
}
// Global Scope: Applied automatically to all queries for this model
protected static function booted(): void
{
static::addGlobalScope('recent', function (Builder $builder) {
$builder->orderBy('created_at', 'desc');
});
}
}
// Usage elsewhere (e.g., a controller)
$publishedPosts = Post::published()->get(); // Uses local scope
$allPostsSorted = Post::all(); // Global scope 'recent' applies automatically
$unsortedPosts = Post::withoutGlobalScope('recent')->get(); // Remove global scope
How it works: Eloquent scopes provide a way to encapsulate common sets of query constraints, making your code more readable and reusable. Local scopes are methods prefixed with `scope` in your model and can be chained onto a query. Global scopes are applied to all queries for a model, but can be temporarily removed using `withoutGlobalScope` or `withoutGlobalScopes`. This pattern ensures consistent filtering logic across your application and avoids repetition.