PHP
Create Reusable Query Filters with Eloquent Local Scopes
Learn how to define and utilize Eloquent local scopes to create reusable query constraints, making your Laravel database queries cleaner and more modular for filtering data.
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
/**
* Scope a query to only include active posts.
*
* @param \Illuminate\Database\Eloquent\Builder $query
* @return \Illuminate\Database\Eloquent\Builder
*/
public function scopeActive($query)
{
return $query->where('is_published', true);
}
/**
* 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 example:
// $activePosts = Post::active()->get();
// $userPosts = Post::byUser(1)->active()->orderBy('created_at', 'desc')->get();
How it works: Eloquent local scopes allow you to define common sets of query constraints that can be easily reused throughout your application. You define a scope method on your model prefixed with `scope`, followed by the desired name (e.g., `scopeActive` for `active()`). These methods receive the query builder instance as their first argument and should return it. This promotes cleaner, more readable, and maintainable code by abstracting common filtering logic into simple, chainable methods.