← Back to all snippets
PHP

Applying Global Query Scopes to Eloquent Models

Learn how to automatically apply query constraints to all Eloquent queries for a specific model using global scopes in Laravel, ensuring consistent data filtering.

<?php
namespace App\Models;

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

class User extends Model
{
    protected static function booted(): void
    {
        static::addGlobalScope('active', function (Builder $builder) {
            $builder->where('is_active', true);
        });
    }

    // To remove a global scope for a specific query:
    // User::withoutGlobalScope('active')->get();
    // User::withoutGlobalScopes()->get();
}

// Example usage:
// $activeUsers = User::all(); // Automatically includes ->where('is_active', true)
// $allUsersIncludingInactive = User::withoutGlobalScope('active')->get();
How it works: Global scopes allow you to add constraints to all queries for a given model. This is particularly useful for ensuring certain data characteristics, like `is_active = true`, are always applied. Define the scope in the model's `booted` method using `addGlobalScope`, providing a name and a closure that applies the desired query modifications. You can temporarily remove global scopes 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