PHP

Creating Reusable Query Constraints with Eloquent Local Scopes

Define and apply reusable query constraints across your Laravel Eloquent models using local scopes, making your queries cleaner, more readable, and maintainable.

<?php

// app/Models/User.php
namespace App\Models;

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

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

    /**
     * Scope a query to only include users of a given type.
     *
     * @param  \Illuminate\Database\Eloquent\Builder  $query
     * @param  string  $type
     * @return \Illuminate\Database\Eloquent\Builder
     */
    public function scopeOfType(Builder $query, string $type)
    {
        return $query->where('type', $type);
    }
}

// Usage Example
// Get all active users
$activeUsers = User::active()->get();

// Get all active admin users
$activeAdmins = User::active()->ofType('admin')->get();

// Get users of a specific type
$editors = User::ofType('editor')->get();

// Chaining with other query methods
$recentActiveUsers = User::active()->orderByDesc('created_at')->limit(10)->get();
How it works: Local scopes allow you to define common sets of query constraints that you can easily reuse throughout your application. You define a local scope by prefixing an Eloquent model method with `scope` (e.g., `scopeActive`). This method accepts an `Illuminate\Database\Eloquent\Builder` instance as its first argument and should return the `$query` builder. You can then call these scopes directly on your model or within other queries, making your code more readable and preventing duplication of query logic.

Need help integrating this into your project?

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

Hire DigitalCodeLabs