Skip to main content

What are Query Scopes?

Query scopes are reusable query constraints that you can define in your models. They allow you to encapsulate common query logic and chain it with other query methods for clean, readable code.
Real-world analogy: Query scopes are like preset filters on a camera. Instead of manually adjusting settings every time (ISO, aperture, shutter speed), you have presets like “Portrait,” “Landscape,” or “Night Mode” that apply multiple settings at once. Similarly, scopes apply multiple query conditions with a single method call.

Basic Scopes

Defining Scopes

Using Scopes

Scope Naming: Scope methods are automatically available without the scope prefix. scopePublished becomes published(), scopeOfType becomes ofType().

Advanced Scope Patterns

Conditional Scopes

Relationship Scopes

Aggregation Scopes

Dynamic Scopes

Parameterized Dynamic Scopes

Builder Pattern Scopes

Global Scopes

Automatic Scopes

Scope Composition

Combining Scopes

Scope Inheritance

Testing Scopes

Unit Testing Scopes

Integration Testing

Performance Optimization

Efficient Scopes

Cached Scopes

Best Practices

1. Keep Scopes Focused

2. Use Descriptive Names

3. Handle Parameters Safely

4. Document Complex Scopes

Next Steps

API Reference

Explore the complete API documentation

Model Methods

Learn about all available model methods