PHP
Create Reusable Local Query Scopes in Eloquent
Organize and reuse common query logic within your Laravel Eloquent models using local scopes for cleaner, more expressive, and maintainable code.
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
// In your Post model (e.g., app/Models/Post.php)
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)
{
return $query->where('is_published', true);
}
/**
* Scope a query to only include posts with more than a given number of views.
*
* @param \Illuminate\Database\Eloquent\Builder $query
* @param int $views
* @return \Illuminate\Database\Eloquent\Builder
*/
public function scopePopular(Builder $query, $views = 100)
{
return $query->where('views_count', '>', $views);
}
}
// Usage:
$publishedPosts = Post::published()->get();
$popularPosts = Post::popular(500)->get();
$publishedPopularPosts = Post::published()->popular(200)->orderBy('created_at', 'desc')->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 model method with `scope`, Eloquent automatically allows you to call that method directly on the model or query builder. This makes your queries more readable, composable, and helps avoid duplicating query logic across different parts of your codebase, promoting a DRY (Don't Repeat Yourself) principle.