Performance: Query scopes
Query scopes affect database query performance and server response time by reusing query logic efficiently.
class User extends Model { public function scopeActiveAdmin($query) { return $query->where('active', 1)->where('role', 'admin'); } } User::activeAdmin()->get();
User::where('active', 1)->where('role', 'admin')->get(); // Repeated in many places without reuse
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Repeated query conditions without scopes | N/A | N/A | N/A | [X] Bad |
| Using query scopes for reusable conditions | N/A | N/A | N/A | [OK] Good |
active in a Laravel model?public function scopePopular($query) {
return $query->where('votes', '>', 100);
}User::popular()->get() return?public function scopeRecent() {
return $this->orderBy('created_at', 'desc');
}activeAndRecent that returns users who are active and created within the last 30 days. Which of the following scope definitions is correct?Pass the test and this pattern moves unknown