PHP

Reusable Eloquent Query Constraints with Local Scopes

Learn to define local scopes in Laravel Eloquent models to encapsulate common query constraints, promoting cleaner, more readable, and reusable code for your queries.

// In App/Models/User.php
class User extends Model
{
    public function scopeActive($query)
    {
        return $query->where('status', 'active');
    }

    public function scopeAdmin($query)
    {
        return $query->where('role', 'admin');
    }

    public function scopeCreatedAfter($query, $date)
    {
        return $query->where('created_at', '>', $date);
    }
}

// Usage in a controller or other part of your application
$activeUsers = App\Models\User::active()->get();

$activeAdmins = App\Models\User::active()->admin()->get();

$recentActiveUsers = App\Models\User::active()->createdAfter('2023-01-01')->get();

// Combining with other query methods
$oldestActiveAdmin = App\Models\User::active()->admin()->orderBy('created_at', 'asc')->first();
How it works: Local scopes allow you to define common sets of constraints that you can easily re-apply to queries on a given model. By prefixing a method in your model with `scope` (e.g., `scopeActive`), it becomes a callable scope. This improves code readability and reusability, helping to avoid duplicating query logic across your application and keeping your controllers cleaner.

Need help integrating this into your project?

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

Hire DigitalCodeLabs