PHP
Implementing Local Scopes for Reusable Eloquent Query Logic
Discover how to define and use local scopes in Laravel Eloquent models to encapsulate common query constraints, making your code cleaner and more reusable.
<?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.
*
* @param \Illuminate\Database\Eloquent\Builder $query
* @return \Illuminate\Database\Eloquent\Builder
*/
public function scopePublished(Builder $query): Builder
{
return $query->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 example in a controller or elsewhere:
// $publishedPosts = Post::published()->get();
// $userPosts = Post::byUser(123)->published()->latest()->get();
How it works: Local 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. When calling a local scope, you simply call the method name without the `scope` prefix (e.g., `Post::published()`). This improves code readability and maintainability by centralizing query logic.