Global Scopes in Laravel

What are Global Scopes in Laravel?

Laravel's Global Scopes are a type of Query Scopes. It allows you to create query constraints that are automatically applied to all model queries. This is useful for maintaining consistency in filtering, such as fetching only active records or using tenant-based filtering.


Origin

Global Scopes were created to enforce query constraints in a reusable way. This fits with Laravel's goal of reducing repetitive code.


Why are Global Scopes Used?

  1. Automate Filtering: Ensures queries always include the necessary limitations.
  2. Improves Code Maintainability: Removes the requirement for duplicate query logic.
  3. Simplifies Multi-Tenant Applications: Automatically apply tenant-based filtering.

Best Practices.

  1. Use for Default Constraints: Use global scopes exclusively on filters that should always be enforced.
  2. Avoid Overuse: Using too many scopes can make it difficult to debug queries.
  3. Disable Scopes as Needed: To temporarily disable a scope, use 'withoutGlobalScope'.

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();

Read more