Scopes
in Laravel are a powerful feature that allows you to encapsulate query
constraints into reusable methods. They help keep your code DRY (Don’t
Repeat Yourself) and make your queries more readable.
Table of Contents
- Types of Scopes
- Local Scopes
- Global Scopes
- Dynamic Scopes
- Scope Features
- Best Practices
1. Types of Scopes
There are two main types of scopes in Laravel:
- Local Scopes: Apply to specific queries when called.
- Global Scopes: Apply to all queries for a model.
2. Local Scopes
Local scopes allow you to define common sets of query constraints that you may easily re-use.
Basic Example
Using Local Scopes
3. Global Scopes
Global scopes allow you to add constraints to all queries for a given model.
Creating a Global Scope:
You can generate a new global scope using the Artisan command
php artisan make:scope ScopeName
. This will automatically create the scope class in your application's app/Models/Scopes
directory.apply
method can add WHERE clauses or other query constraints to modify the query builder instance:Apply the scope to a model:
Alternatively, you can manually register a global scope by overriding the model’s
booted()
method and calling the addGlobalScope()
method:Now all queries for the
User
model will automatically include the age constraint.Anonymous Global Scopes
You can also define global scopes using closures:
Removing Global Scopes
4. Dynamic Scopes
You can create scopes that accept parameters:
5. Scope Features
Chaining Scopes
Combining with Other Query Builder Methods
Conditional Scopes
6. Best Practices
- Keep scopes focused: Each scope should do one specific thing
- Document your scopes: Use PHPDoc to explain what each scope does
- Consider performance: Complex scopes can impact query performance
- Use dynamic scopes judiciously: They’re powerful but can make code harder to understand if overused
If you found this helpful, feel free to share or drop a comment. Happy coding with Laravel! 🧱✨
Social Plugin