PHP
Applying Global Query Scopes in Eloquent
Automatically apply query constraints across multiple Eloquent queries for a model using global scopes, ensuring consistent data filtering throughout your application.
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Builder;
class User extends Model
{
protected static function booted()
{
static::addGlobalScope('active', function (Builder $builder) {
$builder->where('is_active', true);
});
}
}
// Usage (only active users will be retrieved by default)
$activeUsers = User::all();
// You can remove a global scope temporarily
$allUsers = User::withoutGlobalScope('active')->get();
How it works: Global scopes allow you to add constraints to all queries for a given model. In this example, we define a `booted` method in the `User` model to automatically add a `where('is_active', true)` constraint. This means any `User::all()` or `User::where(...)` call will only retrieve active users by default. You can temporarily remove a global scope using `withoutGlobalScope()` for specific queries.