PHP

Apply Global Query Filters with Eloquent Global Scopes

Implement application-wide query constraints on your Laravel Eloquent models using global scopes, ensuring consistent data filtering across all queries automatically.

<?php

// 1. Define the 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
{
    /**
     * Apply the scope to a given Eloquent query builder.
     *
     * @param  \Illuminate\Database\Eloquent\Builder  $builder
     * @param  \Illuminate\Database\Eloquent\Model  $model
     * @return void
     */
    public function apply(Builder $builder, Model $model)
    {
        $builder->where('active', 1);
    }
}

// 2. Apply the Global Scope to an Eloquent Model
namespace App\Models;

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

class Product extends Model
{
    /**
     * The "booted" method of the model.
     *
     * @return void
     */
    protected static function booted()
    {
        static::addGlobalScope(new ActiveScope);

        // You can also add anonymous global scopes
        // static::addGlobalScope('price_range', function (Builder $builder) {
        //     $builder->whereBetween('price', [10, 100]);
        // });
    }

    // To remove a global scope for a specific query:
    // Product::withoutGlobalScope(ActiveScope::class)->get();
    // Product::withoutGlobalScopes()->get(); // removes all
}
How it works: Global scopes allow you to add application-wide query constraints to all queries for a given model. For instance, you might want to only retrieve 'active' users or 'published' posts by default. By applying a global scope in the model's `booted()` method, this constraint is automatically applied to every query, unless explicitly removed using `withoutGlobalScope()` or `withoutGlobalScopes()`. This ensures consistency and reduces repetitive code.

Need help integrating this into your project?

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

Hire DigitalCodeLabs