← Back to all snippets
PHP

Create Reusable Eloquent Query Constraints with Local Scopes

Discover how to define and apply local scopes in Laravel Eloquent models to encapsulate common query logic, making your database queries cleaner and more maintainable.

// In your User model (app/Models/User.php)
class User extends Model
{
    // Define a local scope for active users
    public function scopeActive($query)
    {
        return $query->where('status', 'active');
    }

    // Define another local scope for admin users
    public function scopeAdmin($query)
    {
        return $query->where('role', 'admin');
    }
}

// Usage in your controller, service, or wherever
$activeUsers = User::active()->get();
$activeAdmins = User::active()->admin()->get();
$recentActiveUsers = User::active()->where('created_at', '>=', now()->subDays(7))->get();
How it works: Local scopes provide a convenient way to define common sets of query constraints that can be easily reused throughout your application. By prefixing a method name in your model with `scope`, you create a local scope that can be called directly on the model or a query builder instance. This approach improves code readability, reduces duplication, and makes your database query logic more organized and maintainable across your Laravel project.

Need help integrating this into your project?

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

Hire DigitalCodeLabs