PHP

Encapsulate Query Logic with Eloquent Local Scopes

Discover how to create and use local query scopes in Laravel Eloquent models to encapsulate reusable query logic, making your controllers cleaner and queries more maintainable.

// In your Post model (App/Models/Post.php)
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);
    }
}

// Usage in a controller or elsewhere
// Get all published posts
$publishedPosts = App\Models\Post::published()->get();

// Get all published posts by a specific user
$userPosts = App\Models\Post::published()->byUser(1)->orderBy('title')->get();

// Combine with other query methods
$latestPublishedPosts = App\Models\Post::published()->latest()->take(5)->get();
How it works: This snippet illustrates how to define local query scopes within an Eloquent model. Local scopes (`scopePublished`, `scopeByUser`) allow you to encapsulate common query constraints and reuse them across different parts of your application. They promote cleaner code by moving complex query logic out of controllers and services, making queries more readable and maintainable. Scopes can also be chained together for more specific filtering.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs