Global Scopes in Laravel allow you to define query constraints that are automatically applied to all queries for a model. This is useful for ensuring consistent filtering, such as only retrieving active records or applying tenant-based filtering.
Global Scopes were introduced to provide a reusable way to enforce query constraints across all queries for a model, aligning with Laravel's philosophy of reducing repetitive code.
withoutGlobalScope
to temporarily disable a scope.Create a global scope:
php artisan make:scope ActiveScope
In the ActiveScope
class:
namespace App\Scopes;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Scope;
class ActiveScope implements Scope
{
public function apply(Builder $builder, Model $model)
{
$builder->where('status', 'active');
}
}
Apply the scope in your model:
protected static function booted()
{
static::addGlobalScope(new ActiveScope);
}
To disable the scope temporarily:
Post::withoutGlobalScope(ActiveScope::class)->get();
This approach ensures that default constraints are consistently applied while allowing flexibility when needed.