← Back to all snippets
PHP

Laravel Eloquent Local Scopes for Reusable Query Logic

Organize and reuse query logic in Laravel with Eloquent local scopes. Create custom methods to easily filter or modify your model queries.

// In your App\Models\Product.php

class Product extends Model
{
    // A local scope to get only published products
    public function scopePublished($query)
    {
        return $query->where('published', true);
    }

    // A local scope to get products by category
    public function scopeCategory($query, $categoryId)
    {
        return $query->where('category_id', $categoryId);
    }

    // A local scope for popular products (example)
    public function scopePopular($query)
    {
        return $query->where('views', '>', 100)->orderByDesc('views');
    }
}

// Usage
// Get all published products
$publishedProducts = App\Models\Product::published()->get();

// Get published products in category 1
$electronics = App\Models\Product::published()->category(1)->get();

// Get popular products
$popularProducts = App\Models\Product::popular()->get();
How it works: Local scopes allow you to define common sets of query constraints that you can easily reuse throughout your application. They are defined as methods prefixed with `scope` (e.g., `scopePublished`) within your Eloquent model. When called, the `scope` prefix is omitted, and they can be chained with other query builder methods or other scopes, making your code cleaner and more maintainable.

Need help integrating this into your project?

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

Hire DigitalCodeLabs