PHP

Apply Default Query Constraints with Laravel Eloquent Global Scopes

Learn how to enforce universal query constraints across all Eloquent queries for a specific model using global scopes, ensuring data consistency.

<?php

namespace App\Models\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);
    }
}

// In your User model (e.g., App\Models\User.php):
// use App\Models\Scopes\ActiveUserScope;

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

// To use:
// $activeUsers = User::all(); // Automatically applies 'is_active = true'
// $allUsersIncludingInactive = User::withoutGlobalScope(ActiveUserScope::class)->get();
How it works: Global scopes allow you to add constraints to all queries for a given model. By defining an 'apply' method in a scope class and registering it in your model's 'booted' method, every query will automatically include that constraint. This is ideal for ensuring data consistency (e.g., only active users) without repetitive code. You can temporarily remove a global scope using 'withoutGlobalScope' when needed.

Need help integrating this into your project?

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

Hire DigitalCodeLabs