← Back to all snippets
PHP

Applying Global Query Scopes for Automatic Filtering

Discover how to implement global query scopes in Laravel Eloquent to automatically apply common constraints to all queries for a model, such as 'active' status filtering.

// 1. Define a Global Scope class (e.g., app/Scopes/ActiveUserScope.php)
namespace App\Scopes;

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

class ActiveUserScope implements Scope
{
    public function apply(Builder $builder, Model $model)
    {
        $builder->where('is_active', true);
    }
}

// 2. Apply the Global Scope to your Model (e.g., app/Models/User.php)
namespace App\Models;

use App\Scopes\ActiveUserScope;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable
{
    use HasFactory;

    protected static function boot()
    {
        parent::boot();

        static::addGlobalScope(new ActiveUserScope);
    }

    // To temporarily remove a global scope from a query:
    // User::withoutGlobalScope(ActiveUserScope::class)->get();
    // User::withoutGlobalScopes()->get(); // Remove all global scopes
}

// 3. Any query on User model will now automatically include the 'is_active = true' constraint
$activeUsers = App\Models\User::all(); // Equivalent to User::where('is_active', true)->get();
$activeUsersCount = App\Models\User::count(); // Only counts active users
How it works: Global query scopes allow you to add constraints to all queries performed on a given Eloquent model. This is useful for common filters, such as ensuring only "active" records are retrieved by default, without having to explicitly add the `where` clause every time. To implement, you create a dedicated scope class implementing `Illuminate\Database\Eloquent\Scope` and then register it in your model's `boot` method using `static::addGlobalScope()`. You can temporarily remove global scopes for specific queries using `withoutGlobalScope()` or `withoutGlobalScopes()`.

Need help integrating this into your project?

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

Hire DigitalCodeLabs