PHP
Apply Global Scopes for Automatic Eloquent Query Constraints
Implement global scopes in Eloquent to automatically apply common query constraints across all queries for a model, ensuring consistent filtering.
<?php
namespace App\Models;
use App\Scopes\ActiveUserScope; // Import your global scope
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
use HasFactory;
protected $fillable = ['name', 'email', 'is_active'];
/**
* The "booted" method of the model.
*
* @return void
*/
protected static function booted()
{
static::addGlobalScope(new ActiveUserScope); // Apply the global scope
}
// To temporarily remove a global scope from a query:
// User::withoutGlobalScope(ActiveUserScope::class)->get();
// User::withoutGlobalScopes()->get(); // Remove all global scopes for a query
}
// app/Scopes/ActiveUserScope.php
<?php
namespace App\Scopes;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Scope;
class ActiveUserScope implements Scope
{
/**
* Apply the scope to a given Eloquent query builder.
*
* @param \Illuminate\Database\Eloquent\Builder $builder
* @param \Illuminate\Database\Eloquent\Model $model
* @return void
*/
public function apply(Builder $builder, Model $model)
{
$builder->where('is_active', true);
}
}
How it works: Global scopes allow you to add constraints to all queries executed for a given model. This is useful for enforcing application-wide rules, such as always fetching only 'active' users. To implement, create a class that implements `Illuminate\Database\Eloquent\Scope`, define your `apply` method, and then register it in your model's `booted` method using `static::addGlobalScope()`. You can temporarily remove global scopes using `withoutGlobalScope()` or `withoutGlobalScopes()` when needed, providing flexibility while maintaining default filtering.