← Back to all snippets
PHP

Applying Global Scopes for Consistent Query Filtering

Learn to use Laravel Eloquent global scopes to automatically apply query constraints to all queries of a given model, ensuring data consistency and reducing repetitive code.

// In 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);
    }
}

// In App\Models\Product.php
class Product extends Model
{
    protected static function booted()
    {
        static::addGlobalScope(new ActiveScope);
    }

    // To temporarily remove the scope:
    // Product::withoutGlobalScope(ActiveScope::class)->get();
}

// Usage:
$activeProducts = App\Models\Product::all(); // Automatically applies 'where active = true'
// $allProductsIncludingInactive = App\Models\Product::withoutGlobalScope(ActiveScope::class)->get();
How it works: Global scopes are a powerful way to automatically add constraints to all queries for a given model. This snippet defines an 'ActiveScope' that adds `where('active', true)` to every query executed on the 'Product' model. This ensures that only active products are retrieved by default, promoting consistent data retrieval and simplifying query logic across the application. You can temporarily remove a global scope using withoutGlobalScope().

Need help integrating this into your project?

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

Hire DigitalCodeLabs