PHP

Applying Global Query Scopes for Automatic Filtering in Laravel Eloquent

Implement global query scopes in Laravel Eloquent to automatically apply common WHERE clauses, like `is_active`, across all queries for a specific model.

// 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
{
    public function apply(Builder $builder, Model $model)
    {
        $builder->where('is_active', true);
    }
}

// 2. Apply the scope to your 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 booted()
    {
        static::addGlobalScope(new ActiveScope);
    }

    // To temporarily remove the scope
    public static function allWithInactive()
    {
        return static::withoutGlobalScope(ActiveScope::class)->get();
    }
}

// 3. Usage example
// This will only fetch active products
$activeProducts = App\Models\Product::all();

// This will fetch all products, including inactive ones
$allProducts = App\Models\Product::allWithInactive();
How it works: Global scopes allow you to add constraints to all queries for a given model. In this example, an `ActiveScope` is defined to filter records where `is_active` is true. By applying this scope in the `booted` method of the `Product` model, every query on `Product::class` will automatically include this `where` clause, ensuring consistency. It also shows how to temporarily remove a global scope when needed.

Need help integrating this into your project?

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

Hire DigitalCodeLabs