PHP
Define Reusable Query Constraints with Eloquent Local Scopes
Discover how to create and use local scopes in Laravel Eloquent models to encapsulate common query constraints, making your code cleaner and more maintainable.
// In app/Models/Product.php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Product extends Model
{
// ...
/**
* Scope a query to only include active products.
*
* @param \Illuminate\Database\Eloquent\Builder $query
* @return \Illuminate\Database\Eloquent\Builder
*/
public function scopeActive($query)
{
return $query->where('is_active', true);
}
/**
* Scope a query to only include products in a given category.
*
* @param \Illuminate\Database\Eloquent\Builder $query
* @param string $categorySlug
* @return \Illuminate\Database\Eloquent\Builder
*/
public function scopeCategory($query, $categorySlug)
{
return $query->where('category_slug', $categorySlug);
}
}
// In a controller or service
use App\Models\Product;
// Get all active products
$activeProducts = Product::active()->get();
// Get active products in 'electronics' category
$electronicsProducts = Product::active()->category('electronics')->get();
// You can chain scopes and other query builder methods
$expensiveElectronics = Product::active()->category('electronics')->where('price', '>', 1000)->get();
How it works: Local scopes allow you to define common sets of constraints that you can easily reuse across your application. By prefixing a method with `scope` in your model, you can then call it directly on the model or query builder instance. This improves code readability, prevents duplication, and makes your query logic more modular and manageable.