PHP

Define and Utilize Local and Global Eloquent Scopes

Implement reusable query constraints across your Laravel models using local scopes for specific queries and global scopes for consistently applying conditions.

// app/Models/Product.php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Builder;

class Product extends Model
{
    // Global Scope (e.g., always hide products with status 'archived')
    protected static function boot()
    {
        parent::boot();
        static::addGlobalScope('active', function (Builder $builder) {
            $builder->where('status', '!=', 'archived');
        });
    }

    // Local Scope
    public function scopeAvailable(Builder $query)
    {
        return $query->where('is_available', true)->where('stock', '>', 0);
    }

    public function scopePriceRange(Builder $query, $minPrice, $maxPrice)
    {
        return $query->whereBetween('price', [$minPrice, $maxPrice]);
    }
}

// Usage examples
// Global scope applied automatically
$activeProducts = App\Models\Product::all();

// Retrieve all products including archived (bypassing global scope)
$allProducts = App\Models\Product::withoutGlobalScope('active')->get();

// Using local scopes
$availableProducts = App\Models\Product::available()->get();
$affordableProducts = App\Models\Product::available()->priceRange(10, 50)->get();
How it works: This snippet illustrates the use of both global and local Eloquent scopes. Global scopes, defined in the `boot` method, are automatically applied to all queries on the model (e.g., hiding archived products). They can be temporarily disabled with `withoutGlobalScope()`. Local scopes are methods prefixed with `scope` that return the query builder, allowing for chained, reusable query conditions (e.g., `available()` or `priceRange()`). Both types of scopes help keep query logic organized and prevent repetition, making your code cleaner and more maintainable.

Need help integrating this into your project?

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

Hire DigitalCodeLabs