PHP
Implementing Reusable Local Scopes in Eloquent
Learn to create local scopes in Laravel Eloquent models to define common sets of query constraints, enhancing code reusability and readability.
// In app/Models/Post.php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
/**
* Scope a query to only include published posts.
*/
public function scopePublished($query)
{
return $query->where('published', true)->where('published_at', '<=', now());
}
/**
* Scope a query to only include posts by a given user.
*/
public function scopeByUser($query, $userId)
{
return $query->where('user_id', $userId);
}
}
// Usage example in a controller or elsewhere:
$publishedPosts = App\Models\Post::published()->get();
$userSpecificPublishedPosts = App\Models\Post::published()->byUser(1)->get();
echo "Published Posts:
";
foreach ($publishedPosts as $post) {
echo "- " . $post->title . "
";
}
echo "
User 1's Published Posts:
";
foreach ($userSpecificPublishedPosts as $post) {
echo "- " . $post->title . "
";
}
How it works: Local scopes allow you to define common sets of query constraints that you can easily reuse across your application. By defining methods prefixed with `scope` on your Eloquent model, you can chain these scopes onto your queries, making them more readable, maintainable, and less prone to errors.