PHP

Define Reusable Query Logic with Eloquent Local Scopes

Create encapsulated, reusable query constraints in your Eloquent models, simplifying complex queries and improving code maintainability.

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
    use HasFactory;

    /**
     * Scope a query to only include published posts.
     *
     * @param  \Illuminate\Database\Eloquent\Builder  $query
     * @return \Illuminate\Database\Eloquent\Builder
     */
    public function scopePublished($query)
    {
        return $query->where('status', 'published')
                     ->where('published_at', '<=', now());
    }

    /**
     * Scope a query to only include posts by a given user.
     *
     * @param  \Illuminate\Database\Eloquent\Builder  $query
     * @param  int  $userId
     * @return \Illuminate\Database\Eloquent\Builder
     */
    public function scopeByUser($query, $userId)
    {
        return $query->where('user_id', $userId);
    }
}

// Usage:
// Get all published posts
// $publishedPosts = Post::published()->get();

// Get all published posts by a specific user
// $userPosts = Post::byUser(123)->published()->get();

// You can chain multiple scopes
// $recentPublished = Post::published()->orderByDesc('published_at')->limit(5)->get();
How it works: Local scopes allow you to define common sets of query constraints that you can easily reuse throughout your application. By prefixing a method with `scope` in your model, you can then call that method directly on the Eloquent model or query builder, making your code more readable, modular, and less prone to repetition.

Need help integrating this into your project?

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

Hire DigitalCodeLabs