PHP

Applying Global Query Constraints with Eloquent Global Scopes

Learn to implement Eloquent Global Scopes to automatically apply universal query constraints across all queries for a specific model, ensuring data consistency.

<?php

namespace App\Models;

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

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

// In your User model, register the global scope
class User extends Model
{
    protected $fillable = ['name', 'email', 'is_active', 'age'];

    protected static function booted()
    {
        static::addGlobalScope(new ActiveUserScope);

        // You can also add anonymous global scopes with a key
        static::addGlobalScope('age_restriction', function (Builder $builder) {
            $builder->where('age', '>', 18);
        });
    }
}

// Usage: All these queries will automatically include 'where is_active = 1 AND age > 18'
// Create some test data
User::query()->withoutGlobalScopes()->create(['name' => 'Alice', 'email' => '[email protected]', 'is_active' => true, 'age' => 25]);
User::query()->withoutGlobalScopes()->create(['name' => 'Bob', 'email' => '[email protected]', 'is_active' => false, 'age' => 30]);
User::query()->withoutGlobalScopes()->create(['name' => 'Charlie', 'email' => '[email protected]', 'is_active' => true, 'age' => 17]);
User::query()->withoutGlobalScopes()->create(['name' => 'David', 'email' => '[email protected]', 'is_active' => true, 'age' => 40]);

echo "Active users (age > 18):
";
$activeUsers = User::all(); // Global scopes apply automatically
foreach ($activeUsers as $user) {
    echo "- {$user->name}
"; // Output: Alice, David
}

echo "
All users (without global scopes):
";
// To remove a specific global scope for a query
$allUsers = User::withoutGlobalScope(ActiveUserScope::class)->withoutGlobalScope('age_restriction')->get();
foreach ($allUsers as $user) {
    echo "- {$user->name} (Active: {$user->is_active}, Age: {$user->age})
"; // Output: Alice, Bob, Charlie, David
}

// To remove all global scopes for a query
// $allUsers = User::withoutGlobalScopes()->get();
How it works: This snippet demonstrates how to implement Eloquent Global Scopes. Unlike local scopes, a global scope automatically applies a query constraint to *all* queries executed on a model, unless explicitly removed. This is incredibly useful for enforcing universal conditions like filtering 'active' records across an application or implementing multi-tenancy. The example shows how to define a scope in a dedicated class and anonymously, as well as how to temporarily disable one or all global scopes for specific queries.

Need help integrating this into your project?

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

Hire DigitalCodeLabs