PHP
Implement Reusable Query Constraints with Eloquent Local Scopes
Discover how to define and use local scopes in Laravel Eloquent models to encapsulate common query logic, making your database queries cleaner, more readable, and highly maintainable.
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Builder;
class Post extends Model
{
/**
* Scope a query to only include published posts.
*/
public function scopePublished(Builder $query): void
{
$query->where('is_published', true);
}
/**
* Scope a query to only include posts by a given user.
*/
public function scopeByUser(Builder $query, int $userId): void
{
$query->where('user_id', $userId);
}
}
// Usage example:
$publishedPosts = Post::published()->get();
$userPosts = Post::byUser(123)->published()->get();
$recentPublishedPosts = Post::published()->latest()->take(10)->get();
How it works: Eloquent local scopes allow you to define common sets of query constraints that you can easily reuse across your application. By defining a method starting with `scope` followed by the desired scope name (e.g., `scopePublished`), you can encapsulate specific `where` clauses or other query builders. This significantly improves code readability and maintainability, as you avoid repeating the same query logic in multiple places. Scopes can also be chained together for more complex queries.