← Back to all snippets
PHP

Define Reusable Eloquent Query Scopes

Create local query scopes in Laravel Eloquent models to encapsulate common query constraints, making your code cleaner, more readable, and highly reusable across your application.

// In App\Models\Post.php
namespace App\Models;

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

class Post extends Model
{
    // A simple scope
    public function scopeActive(Builder $query)
    {
        return $query->where('active', 1);
    }

    // A dynamic scope with parameters
    public function scopePopular(Builder $query, $threshold = 100)
    {
        return $query->where('views', '>', $threshold);
    }
}

// Usage:
// Get all active posts
$activePosts = App\Models\Post::active()->get();

// Get all popular posts (views > 100)
$popularPosts = App\Models\Post::popular()->get();

// Get posts with views > 200
$veryPopularPosts = App\Models\Post::popular(200)->get();

// Combine scopes and other queries
$recentActivePosts = App\Models\Post::active()->where('created_at', '>', now()->subWeek())->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` in your model (e.g., `scopeActive`), Eloquent automatically makes it available as a callable method on the model (e.g., `Post::active()`). Scopes can also accept arguments, providing flexibility to apply dynamic conditions to your queries, greatly improving code organization and maintainability.

Need help integrating this into your project?

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

Hire DigitalCodeLabs