PHP

Implement Application-Wide Query Constraints with Eloquent Global Scopes

Apply universal query constraints across your entire Laravel application using Eloquent Global Scopes, ensuring data consistency and security.

// 1. Define a Global Scope Class (e.g., App\Scopes\ActiveScope.php)
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('active', true);
    }
}

// 2. Apply the Global Scope to a Model (e.g., App\Models\Product.php)
namespace App\Models;

use App\Scopes\ActiveScope;
use Illuminate\Database\Eloquent\Model;

class Product extends Model
{
    protected static function boot()
    {
        parent::boot();
        static::addGlobalScope(new ActiveScope);
    }
}

// Example Usage:
// This will automatically apply `where('active', true)`
$activeProducts = Product::all();

// To remove the global scope for a specific query
$allProductsIncludingInactive = Product::withoutGlobalScope(ActiveScope::class)->get();
// Or remove all global scopes
$allProducts = Product::withoutGlobalScopes()->get();
How it works: Global Scopes allow you to add constraints to all queries for a given model. In this example, the `ActiveScope` ensures that all `Product` queries automatically filter for `active` products. This is highly useful for implementing application-wide filters like multi-tenancy or showing only active content. You can temporarily remove global scopes for specific queries if needed.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs