PHP
Defining Reusable Local Query Scopes in Eloquent
Encapsulate common query logic into reusable local scopes in your Laravel Eloquent models, making your code cleaner and more maintainable.
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
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($query)
{
return $query->where('status', 'published');
}
/**
* Scope a query to only include posts with a specific tag.
*
* @param \Illuminate\Database\Eloquent\Builder $query
* @param string $tag
* @return \Illuminate\Database\Eloquent\Builder
*/
public function scopeWithTag($query, $tag)
{
return $query->whereHas('tags', function ($q) use ($tag) {
$q->where('name', $tag);
});
}
// Define a relationship to tags (assuming many-to-many)
public function tags()
{
return $this->belongsToMany(Tag::class);
}
// Example usage:
// $publishedPosts = Post::published()->get();
// $recentPublishedPosts = Post::published()->orderBy('created_at', 'desc')->take(5)->get();
// $phpPosts = Post::withTag('PHP')->published()->get();
}
How it works: Local query scopes allow you to define common query constraints in your Eloquent models, making your code more readable and reusable. A scope method begins with `scope` followed by the PascalCased name of the scope (e.g., `scopePublished`). When calling the scope, you simply reference its name in camelCase (e.g., `Post::published()`). Scopes can also accept arguments, enabling dynamic filtering. They can be chained with other query builder methods or even other scopes, providing a powerful way to build complex queries cleanly.