← Back to all snippets
PHP

Applying Global Scopes for Universal Query Constraints

Discover how to implement global scopes in Laravel Eloquent to automatically apply query constraints across all queries for a given model, enhancing code consistency.

<?php

// app/Scopes/ActiveScope.php
namespace App\Scopes;

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

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

// app/Models/Product.php
namespace App\Models;

use App\Scopes\ActiveScope;
use Illuminate\Database\Eloquent\Model;

class Product extends Model
{
    protected static function booted()
    {
        static::addGlobalScope(new ActiveScope);
    }
}

// Usage Example
$activeProducts = Product::all(); // Automatically applies `where('is_active', true)`

// To remove the global scope for a specific query:
$allProducts = Product::withoutGlobalScope(ActiveScope::class)->get();

// To remove all global scopes:
$allProductsWithAllScopesRemoved = Product::withoutGlobalScopes()->get();
How it works: Global scopes allow you to add constraints to all queries for a given model. This is useful for things like multi-tenancy, soft-deletes (though Laravel provides this out of the box), or ensuring only "active" records are retrieved by default. You define a class that implements the `Illuminate\Database\Eloquent\Scope` interface and its `apply()` method. Then, you register this scope in your model's `booted()` method using `static::addGlobalScope()`. You can temporarily remove global scopes using `withoutGlobalScope()` or `withoutGlobalScopes()` 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