PHP
Implement Global Query Scopes for Automatic Conditions
Apply default query conditions across all Eloquent queries for a model using global scopes, ensuring consistent data filtering without repeating code.
// In app/Models/Scopes/ActiveUserScope.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 app/Models/User.php
namespace App\Models;
use App\Models\Scopes\ActiveUserScope;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
use HasFactory;
protected static function booted()
{
static::addGlobalScope(new ActiveUserScope);
}
}
// Usage:
// User::all(); // Automatically applies where('is_active', true)
// User::withoutGlobalScope(ActiveUserScope::class)->get(); // Bypass the scope
How it works: Global query scopes allow you to add constraints to all queries for a given model. This is useful for "soft-deleting" or ensuring only "active" records are retrieved by default. To create one, define a class implementing `Illuminate\Database\Eloquent\Scope` with an `apply` method. Then, register this scope in your model's `booted()` method using `static::addGlobalScope()`. You can temporarily remove a global scope for specific queries using `withoutGlobalScope()`.