PHP

Utilizing Local Query Scopes for Reusable Constraints

Enhance your Laravel Eloquent queries by defining reusable local scopes, allowing cleaner, more maintainable code for common query conditions.

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Product extends Model
{
    protected $fillable = ['name', 'price', 'is_published'];

    /**
     * Scope a query to only include published products.
     *
     * @param  \Illuminate\Database\Eloquent\Builder  $query
     * @return \Illuminate\Database\Eloquent\Builder
     */
    public function scopePublished($query)
    {
        return $query->where('is_published', true);
    }

    /**
     * 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 \Illuminate\Database\Eloquent\Builder
     */
    public function scopePriceRange($query, $minPrice, $maxPrice)
    {
        return $query->whereBetween('price', [$minPrice, $maxPrice]);
    }

    // Example usage:
    // Product::published()->get();
    // Product::published()->priceRange(10, 100)->orderBy('price')->get();
}
How it works: This snippet shows how to define and use local query scopes in Eloquent. A local scope is a method prefixed with `scope` (e.g., `scopePublished`) in your model that accepts the query builder instance as its first argument. It allows you to encapsulate common query logic into a single, reusable method. You can then chain these scopes directly onto your Eloquent queries, making your code more readable and maintainable by avoiding repetition of query constraints.

Need help integrating this into your project?

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

Hire DigitalCodeLabs