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
Laravel Cashier & Stripe: A Comprehensive Billing Guide for Subscriptions
# Laravel Cashier & Stripe: A Comprehensive Billing Guide for Subscriptions Laravel Cashier simplifies the complex world of subscription billing with Stripe, p...
Mastering Laravel Sail: Your Guide to Effortless Local Development
## Mastering Laravel Sail: Your Guide to Effortless Local Development Laravel Sail is a lightweight command-line interface for interacting with Laravel's defau...
Laravel Folio: Streamlining File-Based Routing in Laravel
# Laravel Folio: Streamlining File-Based Routing in Laravel Laravel Folio is a powerful, elegant, and incredibly simple file-based router for Laravel applicati...
Mastering Laravel Horizon: Advanced Queue Management and Monitoring
# Mastering Laravel Horizon: Advanced Queue Management and Monitoring Laravel applications often rely on queues for handling time-consuming tasks in the backgr...