PHP
Reusable Query Constraints with Eloquent Local Scopes
Discover how to create and utilize local scopes in Laravel Eloquent models to define reusable sets of query constraints, enhancing code readability and maintainability.
// In your App\Models\Post model:
// public function scopePublished($query) { return $query->where('published', true); }
// public function scopeRecent($query) { return $query->where('created_at', '>=', now()->subDays(7)); }
// public function scopeByUser($query, $userId) { return $query->where('user_id', $userId); }
// Usage:
// Get all published posts
$publishedPosts = App\Models\Post::published()->get();
// Get recent posts
$recentPosts = App\Models\Post::recent()->get();
// Combine scopes
$publishedRecentPosts = App\Models\Post::published()->recent()->get();
// Scope with parameters
$userPosts = App\Models\Post::byUser(123)->get();
// Scopes can be chained with other query builder methods
$popularPublishedPosts = App\Models\Post::published()
->where('views', '>', 100)
->orderByDesc('views')
->limit(5)
->get();
How it works: Local scopes allow you to define common sets of query constraints that can be easily reused across your application. By prefixing a model method with `scope`, you can call it directly on the model or an existing query builder instance. This approach makes your database queries more readable, maintainable, and prevents code duplication, promoting a cleaner codebase.