← Back to all snippets
PHP

Implementing Global Query Scopes in Laravel Eloquent

Learn to apply universal query constraints across all Eloquent queries for a model using global scopes, perfect for multi-tenancy or status filtering without repetition.

<?php

namespace App\Models;

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

// 1. Define the Global Scope Class
class ActiveUserScope implements Scope
{
    public function apply(Builder $builder, Model $model)
    {
        $builder->where('status', 'active');
    }
}

// 2. Apply the Global Scope to your Model
class User extends Model
{
    protected static function booted()
    {
        static::addGlobalScope(new ActiveUserScope);

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

    // 3. Temporarily remove a global scope
    public function getAllUsersIgnoreActiveScope()
    {
        return User::withoutGlobalScope(ActiveUserScope::class)->get();
    }

    // 4. Remove all global scopes
    public function getAllUsersIgnoreAllScopes()
    {
        return User::withoutGlobalScopes()->get();
    }
}

// Usage example:
// $activeUsers = User::all(); // Automatically applies 'status = active'
// $allUsersIncludingInactive = (new User())->getAllUsersIgnoreActiveScope();
How it works: Eloquent global scopes allow you to apply constraints to all queries executed for a given model. This is incredibly useful for scenarios like multi-tenancy, soft-deletes (which is an out-of-the-box global scope), or filtering by a 'status' field. You define a scope class implementing the `Scope` interface, then register it in your model's `booted` method. You can temporarily remove specific global scopes using `withoutGlobalScope()` or all of them with `withoutGlobalScopes()` when you need to fetch records that fall outside the global constraint.

Need help integrating this into your project?

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

Hire DigitalCodeLabs