PHP
Creating Reusable Query Logic with Eloquent Local Scopes
Define reusable query constraints in Laravel Eloquent using local scopes, making your database queries more readable, organized, and maintainable.
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
/**
* Scope a query to only include published posts.
*/
public function scopePublished(Builder $query): void
{
$query->where('published', true);
}
/**
* Scope a query to only include posts of a given type.
*/
public function scopeOfType(Builder $query, string $type): void
{
$query->where('type', $type);
}
}
// Usage Example:
$publishedArticles = Post::published()->ofType('article')->get();
$draftReviews = Post::where('published', false)->ofType('review')->get();
How it works: Local scopes provide a powerful way to define common sets of query constraints that can be easily reused across your application, improving code readability and maintainability. The `scopePublished` method adds a `where('published', true)` clause, allowing you to simply call `Post::published()` to retrieve all published posts. `scopeOfType` demonstrates a dynamic scope that accepts parameters, enabling more flexible filtering based on the 'type' attribute.