PHP

Reusing Query Logic with Eloquent Local Scopes

Learn to encapsulate and reuse common query constraints across your Laravel application by defining and utilizing Eloquent local query scopes in your models for clean code.

<?php

namespace App\Models;

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

class Product extends Model
{
    /**
     * Scope a query to only include active products.
     *
     * @param  \Illuminate\Database\Eloquent\Builder  $query
     * @return void
     */
    public function scopeActive(Builder $query): void
    {
        $query->where('status', 'active');
    }

    /**
     * Scope a query to only include products within a given price range.
     *
     * @param  \Illuminate\Database\Eloquent\Builder  $query
     * @param  float  $minPrice
     * @param  float  $maxPrice
     * @return void
     */
    public function scopePriceRange(Builder $query, float $minPrice, float $maxPrice): void
    {
        $query->whereBetween('price', [$minPrice, $maxPrice]);
    }

    // Example usage in a controller:
    // $activeProducts = Product::active()->get();
    // $affordableActiveProducts = Product::active()->priceRange(10, 50)->get();
}
How it works: Local scopes allow you to define common sets of query constraints that you can easily reuse throughout your application. To define a local scope, prefix an Eloquent model method with `scope` (e.g., `scopeActive`). The method always receives the query builder instance as its first argument. You can then call these scopes directly on your model or within other queries, making your code more readable, maintainable, and DRY (Don't Repeat Yourself).

Need help integrating this into your project?

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

Hire DigitalCodeLabs