PHP

Creating Reusable Query Filters with Eloquent Local Scopes

Learn how to define and use local scopes in Laravel Eloquent models to encapsulate common query constraints, improve code reusability, and keep your controllers clean.

// In App\Models\Product.php
class Product extends Model
{
    // A local scope for active products
    public function scopeActive($query)
    {
        return $query->where('is_active', true);
    }

    // A local scope for featured products
    public function scopeFeatured($query)
    {
        return $query->where('is_featured', true);
    }

    // A local scope with parameters
    public function scopePriceRange($query, $minPrice, $maxPrice)
    {
        return $query->whereBetween('price', [$minPrice, $maxPrice]);
    }
}

// Usage in controllers or elsewhere
$activeProducts = Product::active()->get();
$featuredActiveProducts = Product::active()->featured()->get();
$affordableProducts = Product::priceRange(10, 100)->get();
$complexQuery = Product::active()->featured()->priceRange(50, 200)->orderBy('price')->get();
How it works: Local scopes allow you to define common sets of query constraints that you can easily re-use throughout your application. By prefixing a method name with `scope` in your Eloquent model (e.g., `scopeActive`), you can call that method directly on your model or query builder (e.g., `Product::active()`). Scopes can also accept arguments, making them highly flexible for dynamic filtering. This pattern significantly improves code readability and maintainability by centralizing query logic.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs