Laravel 12 Query Scopes: A Step-by-Step Guide with Examples

Query Scopes
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
  1. Types of Scopes
  2. Local Scopes
  3. Global Scopes
  4. Dynamic Scopes
  5. Scope Features
  6. Best Practices 
1. Types of Scopes
There are two main types of scopes in Laravel:
  1. Local Scopes: Apply to specific queries when called.
  2. 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 
Local Scopes 
Using Local Scopes
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.
Creating a Global Scope 
The apply method can add WHERE clauses or other query constraints to modify the query builder instance:
modify the query builder instance  
Apply the scope to a model:
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:
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:
Anonymous Global Scopes 
Removing Global Scopes
Removing Global Scopes  
4. Dynamic Scopes
You can create scopes that accept parameters:
Dynamic Scopes 
5. Scope Features
Chaining Scopes
Chaining Scopes  
Combining with Other Query Builder Methods
Combining with Other Query Builder Methods 
Conditional Scopes
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 
Scopes are a powerful tool in Laravel that can significantly improve the organization and readability of your database queries while reducing code duplication.
 
If you found this helpful, feel free to share or drop a comment. Happy coding with Laravel! 🧱✨