PHP

Implementing Global Query Constraints with Laravel Eloquent Global Scopes

Master applying default, site-wide query constraints to your Laravel Eloquent models automatically using Global Scopes, ideal for multi-tenancy or soft deletes.

<?php

// 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 scope to a model (e.g., App/Models/User.php)
namespace App\Models;

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

class User extends Model
{
    protected static function booted()
    {
        static::addGlobalScope(new ActiveUserScope);
    }
}

// 3. Usage (automatically applied)
$activeUsers = App\Models\User::all(); // Only active users
$allUsersIncludingInactive = App\Models\User::withoutGlobalScope(ActiveUserScope::class)->get(); // Bypass scope
How it works: Global scopes allow you to add constraints to all queries for a given model automatically. This is highly useful for implementing 'soft deletes,' multi-tenancy, or ensuring only active records are retrieved by default across your application. The `apply` method modifies the query builder, and you can temporarily remove a global scope 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