Global Scopes

What are Global Scopes?

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.


Origin

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.


Why are they important?

  1. Automates Filtering: Ensures queries consistently include necessary constraints.
  2. Improves Code Maintainability: Reduces the need to duplicate query logic.
  3. Simplifies Multi-Tenant Applications: Applies tenant-based filtering automatically.

Best Practices

  1. Use for Default Constraints: Apply global scopes only for filters that should always be enforced.
  2. Avoid Overuse: Overusing scopes can make queries harder to debug.
  3. Disable Scopes When Needed: Use withoutGlobalScope to temporarily disable a scope.

Example in Action

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.