Defining Scopes
Scopes are defined as static methods in your model with the prefixscope followed by a PascalCase name:
Basic Usage
Applying a Single Scope
Combining Multiple Scopes
Scopes with Parameters
Combining with Query Builder
Scopes integrate seamlessly with other QueryBuilder methods:Practical Examples
Blog Post Model
Blog Post Model
Product Model
Product Model
Advanced Scope Patterns
Scopes with Multiple Conditions
Scopes with OR Conditions
Conditional Scopes
Implementation Details
FromModel.js:169-182, scopes are implemented using the _applyScope method:
Best Practices
Benefits of Scopes
Scopes provide several key advantages:
- Reusability: Define once, use everywhere
- Readability:
User.scope("active", "verified")vs multiplewhere()calls - Maintainability: Change logic in one place
- Composability: Combine scopes for complex queries
- Testability: Easy to test scopes in isolation
Testing Scopes
Common Pitfalls
Summary
| Usage | Example |
|---|---|
| Apply single scope | User.scope("active") |
| Apply multiple scopes | User.scope("active", "verified") |
| Scope with parameters | User.scope("role", "admin") |
| Chain scopes | User.scope("active").scope("recent") |
| Combine with query builder | User.scope("active").where("country", "ES") |