PHP

Applying Global Query Scopes in Laravel Eloquent

Understand how to define and apply global scopes in Laravel Eloquent to automatically add constraints to all queries for a given model, ensuring consistent filtering.

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Builder;

// App/Models/Product.php
class Product extends Model
{
    protected static function boot()
    {
        parent::boot();

        static::addGlobalScope('active', function (Builder $builder) {
            $builder->where('is_active', true);
        });
    }

    // Method to allow retrieving all products, including inactive ones
    public static function withInactive()
    {
        return (new static())->withoutGlobalScope('active');
    }
}

// Usage:
$activeProducts = Product::all(); // Automatically applies where('is_active', true)

// Get products without the 'active' global scope
$allProducts = Product::withoutGlobalScope('active')->get();

// Alternatively, using the custom method:
$allProductsViaMethod = Product::withInactive()->get();

foreach ($activeProducts as $product) {
    echo "Active Product: " . $product->name . "
";
}
How it works: Global scopes in Eloquent allow you to add constraints to all queries of a given model. By defining `addGlobalScope` in the `boot` method of the `Product` model, every `Product::query()` will automatically include `where('is_active', true)`. This ensures consistency across the application. You can temporarily remove a global scope using `withoutGlobalScope()` for specific queries when you need to retrieve all records, including those filtered by the scope.

Need help integrating this into your project?

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

Hire DigitalCodeLabs