Posted on: September 23, 2025 08:31 AM
Posted by: Renato
Categories: Laravel
Views: 336
Laravel 12.29: Disable all global scopes except chosen
Last updated on Sep 18, 2025
New in Laravel 12.29: withoutGlobalScopesExcept()
Laravel 12.29 introduces a handy new Eloquent method: withoutGlobalScopesExcept(). This lets you disable all global scopes on a query except the ones you explicitly want to keep.
What it does
Previously, you could:
- Use
withoutGlobalScope()to remove one scope. - Use
withoutGlobalScopes()to remove all or several scopes.
Now, with:
Post::withoutGlobalScopesExcept(['tenant'])->get();
You remove all global scopes except tenant.
Example
class Post extends Model
{
protected static function booted()
{
static::addGlobalScope('published', fn ($q) => $q->where('published', true));
static::addGlobalScope('tenant', fn ($q) => $q->where('tenant_id', auth()->id()));
}
}
// Only keep the tenant scope:
$posts = Post::withoutGlobalScopesExcept(['tenant'])->get();
Why it matters
This feature makes queries more expressive and concise. Instead of manually disabling multiple scopes or re‑adding conditions, you can whitelist just the ones you need.
For details, see PR #56957.
[12.x] Add withoutGlobalScopesExcept() to keep only specified global scopes #56957
This PR introduces a new Eloquent query builder method:
withoutGlobalScopesExcept(array $scopes = [])
This method allows disabling all global scopes except the ones explicitly listed.
Example usage
class Post extends Model
{
protected static function booted()
{
static::addGlobalScope('published', fn ($q) => $q->where('published', true));
static::addGlobalScope('not_deleted', fn ($q) => $q->whereNull('deleted_at'));
static::addGlobalScope('tenant', fn ($q) => $q->where('tenant_id', auth()->id()));
static::addGlobalScope('locale', fn ($q) => $q->where('locale', app()->getLocale()));
static::addGlobalScope('approved', fn ($q) => $q->where('approved', true));
}
}
Current approach
// Want to keep only the "tenant" scope
// Option 1: Disable all, then reapply manually
$posts = Post::withoutGlobalScopes()
->where('tenant_id', auth()->id())
->get();
// Option 2: Disable unwanted scopes using withoutGlobalScopes([])
$posts = Post::withoutGlobalScopes([
'published',
'not_deleted',
'locale',
'approved',
])->get();
With this PR
// Disable all scopes except "tenant" $posts = Post::withoutGlobalScopesExcept(['tenant'])->get();
Fonte: nabilhassen
Donate to Site
Renato
Developer