eloquent Junior

What are query scopes?

Short Answer

Query scopes are reusable query constraints defined as methods on Eloquent models, keeping query logic organized and DRY.

Detailed Answer

Query scopes encapsulate commonly used WHERE clauses into named methods: Local scopes: - Defined as methods with 'scope' prefix - Called without the prefix: Post::published() - Can accept parameters: Post::inCategory(5) - Chainable with other query methods Global scopes: - Apply constraints to ALL queries for a model - Examples: SoftDeletes (only non-deleted records) - Can be removed with withoutGlobalScope() Benefits: DRY code, readable queries, testable constraints, easy maintenance.

Code Example

Example
<?php
// Local scopes on Post model
public function scopePublished($query)
{
    return $query->whereNotNull('published_at')
                ->where('published_at', '<=', now());
}

public function scopeInCategory($query, $categoryId)
{
    return $query->where('category_id', $categoryId);
}

public function scopePopular($query)
{
    return $query->where('views_count', '>=', 1000);
}

// Usage - clean, readable queries
$posts = Post::published()->inCategory(5)->popular()->get();

// Dynamic scoping
$query = Post::query();
if ($request->has('status')) {
    $query->where('status', $request->status);
}
$posts = $query->get();

Interview Tip

Show how scopes make queries readable: "Post::published()->popular()->latest()" is self-documenting compared to nested where() calls.