PHP

Create Reusable Query Constraints with Eloquent Local Scopes

Implement local scopes in your Eloquent models to define common sets of query constraints, making your code cleaner, more readable, and maintainable.

use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;

// In app/Models/Post.php
class Post extends Model
{
    // Local Scope: Posts published in the last 7 days
    public function scopeRecent(Builder $query): Builder
    {
        return $query->where('published_at', '>=', now()->subDays(7));
    }

    // Local Scope: Posts with 'featured' status
    public function scopeFeatured(Builder $query): Builder
    {
        return $query->where('is_featured', true);
    }
}

// Usage in a controller or service
// Get all recent posts
$recentPosts = App\Models\Post::recent()->get();

// Get all featured and recent posts
$featuredRecentPosts = App\Models\Post::featured()->recent()->get();

// Get recent posts filtered by a keyword
$recentSearchResults = App\Models\Post::recent()->where('title', 'like', '%Laravel%')->get();
How it works: Local scopes allow you to define common sets of query constraints that can be easily reused across your application. By prefixing a method name with `scope` (e.g., `scopeRecent`), Eloquent automatically makes it available as a dynamic query method on your model. This promotes clean, readable code by abstracting complex query logic into meaningful method calls, improving maintainability and reducing repetition.

Need help integrating this into your project?

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

Hire DigitalCodeLabs