Eloquent Scopes are one of Laravel’s most elegant features for organizing database queries and keeping your codebase clean.
Instead of repeating query conditions across controllers and services, scopes allow you to define reusable constraints directly inside the model.
## What Are Eloquent Scopes?
Eloquent Scopes are reusable query methods defined inside your Eloquent models.
Laravel supports two types:
- Local Scopes
- Global Scopes
## Local Scopes
Local scopes are perfect for repeated query conditions.
### Example
```php
class Post extends Model
{
public function scopePublished($query)
{
return $query->where('published', true);
}
public function scopeLatestPublished($query)
{
return $query->published()
->orderByDesc('published_at');
}
}
Usage
Post::published()->get();
Post::latestPublished()->paginate(10);
The result:
Cleaner queries
Better readability
Less duplication
Why Scopes Matter
Without scopes, query logic often spreads across:
Controllers
Services
Repositories
Scopes centralize query logic inside the model, improving:
Maintainability
Readability
Long-term scalability
Global Scopes
Global scopes apply constraints automatically to all queries.
Common Use Cases
Soft deletes
Multi-tenant filtering
Active-only records
class ActiveScope implements Scope
{
public function apply(Builder $builder, Model $model)
{
$builder->where('is_active', true);
}
}
Best Practices
Use clear and meaningful scope names
Keep scopes focused on query logic
Combine scopes for flexible queries
Prefer scopes over duplicated conditions
Final Thoughts
Eloquent Scopes don’t just shorten queries —
they significantly improve the structure of your Laravel applications.
A must-use feature for every Laravel developer 💜
Laravel Eloquent Scopes: Cleaner & Reusable Queries
Key Takeaways
- Laravel Eloquent Scopes help you write cleaner, reusable, and expressive database queries by encapsulating query logic directly inside your models.
Added a complete explanation of Eloquent Scopes with real-world examples.
Mohamed Shahin
Software Engineer
You might also like
Contributing to Laravel Open Source: How to Report Bugs with Pull Requests
Laravel, known for its elegant syntax and robust features, thrives on its vibrant open-source community. Recently, Taylor Otwell, the creator of Laravel, announ...
Leveraging Laravel Octane for High-Performance PHP Applications
Introduction: Unleashing Performance with Laravel Octane As the Laravel ecosystem continues to evolve, developers are constantly seeking ways to build faster, m...
Implementing Robust Approval Workflows in Laravel
# Implementing Robust Approval Workflows in Laravel Approval workflows are a crucial feature in many web applications, allowing for content moderation, task va...
Unlocking Real-time: A Comprehensive Guide to Laravel Reverb
# Unlocking Real-time: A Comprehensive Guide to Laravel Reverb Laravel Reverb is a powerful, first-party WebSocket server for Laravel applications, designed to...