PHP
Create Reusable Query Logic with Laravel Eloquent Local Scopes
Define and utilize local query scopes in Laravel Eloquent models to encapsulate common query constraints, promoting code reusability and cleaner controllers.
// In App/Models/Post.php
class Post extends Model
{
public function scopePublished($query)
{
return $query->where('published', true)->where('published_at', '<=', now());
}
}
// In a controller or elsewhere
$publishedPosts = App\Models\Post::published()->orderBy('published_at', 'desc')->get();
How it works: Local scopes allow you to define common sets of constraints that can be easily reused throughout your application. By defining a `scopePublished` method on the `Post` model, you can then call `Post::published()` as a method on the Eloquent model to retrieve only published posts. This approach makes your query code more readable, maintainable, and prevents duplication of query logic.