PHP

Creating Reusable Local Query Scopes in Eloquent

Discover how to define and utilize local query scopes in Laravel Eloquent models to encapsulate and reuse common query constraints, making your code cleaner and more efficient.

namespace App\Models;

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

class Post extends Model
{
    /**
     * Scope a query to only include published posts.
     *
     * @param  \Illuminate\Database\Eloquent\Builder  $query
     * @return \Illuminate\Database\Eloquent\Builder
     */
    public function scopePublished(Builder $query): Builder
    {
        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(Builder $query, int $userId): Builder
    {
        return $query->where('user_id', $userId);
    }
}

// Usage in a controller or elsewhere:
// Get all published posts
$publishedPosts = Post::published()->get();

// Get published posts by a specific user
$userPosts = Post::published()->byUser(123)->get();
How it works: Local query scopes allow you to define common sets of constraints that you can easily reuse throughout your application. They are defined as methods prefixed with `scope` in your Eloquent model, accepting an `Illuminate\Database\Eloquent\Builder` instance as their first argument. You can then chain these scopes onto your model queries, making your code more readable and maintaining a 'Don't Repeat Yourself' (DRY) principle.

Need help integrating this into your project?

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

Hire DigitalCodeLabs