PHP

Reusable Query Logic with Local Scopes

Create powerful, reusable query constraints in Laravel Eloquent models using local scopes to keep your controller and repository code clean and DRY.

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

    public function scopeOfType($query, $type)
    {
        return $query->where('type', $type);
    }
}

// Usage in a Controller or elsewhere
$publishedPosts = App\Models\Post::published()->get();
$draftArticles = App\Models\Post::ofType('article')->where('status', 'draft')->get();
How it works: Local scopes allow you to define common sets of query constraints that you can easily reuse throughout your application. By prefixing a method with `scope` in your Eloquent model (e.g., `scopePublished`), you can then call that scope directly on the model or a relationship query (e.g., `Post::published()`). This promotes cleaner, more readable code and adheres to the DRY principle.

Need help integrating this into your project?

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

Hire DigitalCodeLabs