PHP
Reusable Query Logic with Laravel Eloquent Local Scopes
Define and reuse common query constraints across your Laravel Eloquent models using local scopes, promoting DRY principles and cleaner code.
// In App\Models\Post.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 in a controller or elsewhere
use App\Models\Post;
// Get all published posts
$publishedPosts = Post::published()->get();
// Get all published posts by a specific user (e.g., user ID 1)
$userPublishedPosts = Post::published()->byUser(1)->get();
// You can chain multiple scopes and other query methods
$latestPublishedPosts = Post::published()->latest()->take(5)->get();
echo "Published Posts:
";
foreach ($publishedPosts as $post) {
echo "- " . $post->title . "
";
}
echo "
Published Posts by User 1:
";
foreach ($userPublishedPosts as $post) {
echo "- " . $post->title . "
";
}
How it works: Laravel Eloquent local scopes allow you to define common sets of query constraints that can be easily reused throughout your application. By defining methods prefixed with `scope` (e.g., `scopePublished`) in your model, you can then call these methods directly on the model or its query builder (e.g., `Post::published()`). This promotes the Don't Repeat Yourself (DRY) principle, keeps your controller or service logic cleaner, and makes your queries more readable and maintainable. Scopes can also accept arguments for dynamic filtering.