PHP

Applying Reusable Query Logic with Eloquent Local Scopes

Define and reuse common query constraints across your Laravel Eloquent models using local scopes, making your code cleaner, more modular, and easier to maintain.

// In App\Models\Post.php
class Post extends Model
{
    public function scopePublished($query)
    {
        return $query->where('published_at', '<=', now());
    }

    public function scopePopular($query)
    {
        return $query->orderByDesc('views')->limit(10);
    }
}

// Usage
$publishedPosts = App\Models\Post::published()->get();
$popularPublishedPosts = App\Models\Post::published()->popular()->get();
$publishedPostsByAuthor = App\Models\Post::published()->where('user_id', 1)->get();
How it works: Eloquent local scopes allow you to define common sets of query constraints that you can easily reuse throughout your application. By defining a method prefixed with `scope` in your model, you can then call that scope directly on your model or query builder instance. This approach helps keep your controllers and other parts of your application lean, improves code readability, and centralizes query logic, making it easier to manage and modify.

Need help integrating this into your project?

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

Hire DigitalCodeLabs