PHP
Create Reusable Query Logic with Eloquent Local Scopes
Learn to define and use local scopes in Laravel Eloquent models, allowing you to encapsulate common query constraints for easy reuse and cleaner code.
// 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.
*
* @param \Illuminate\Database\Eloquent\Builder $query
* @return \Illuminate\Database\Eloquent\Builder
*/
public function scopePublished($query)
{
return $query->where('is_published', true)->where('published_at', '<=', now());
}
/**
* Scope a query to only include posts by a given user.
*
* @param \Illuminate\Database\Eloquent\Builder $query
* @param int $userId
* @return \Illuminate\Database\Eloquent\Builder
*/
public function scopeByUser($query, $userId)
{
return $query->where('user_id', $userId);
}
}
// Example Usage
// Get all published posts
$publishedPosts = App\Models\Post::published()->get();
// Get all unpublished posts by a specific user
$userPosts = App\Models\Post::byUser(5)->where('is_published', false)->get();
// Combine scopes
$publishedUserPosts = App\Models\Post::published()->byUser(1)->get();
How it works: Local scopes provide a convenient way to define common sets of query constraints that can be reused throughout your application. By prefixing a method name with `scope` (e.g., `scopePublished`), you can then call that scope directly on your Eloquent model or query builder (e.g., `Post::published()`). This makes your code more readable, maintainable, and prevents duplication of query logic, especially for complex or frequently used conditions.