Query scopes help you reuse common database query parts easily. They keep your code clean and simple.
You want to filter users who are active in many places in your app.
You need to reuse a common condition like 'only published posts' in different queries.
You want to keep your database queries organized inside your model.
You want to avoid repeating the same query code in multiple controllers or views.
Syntax
Laravel
public function scopeName($query, $param1, $param2)
{
return $query->where(...);
}
Scope methods always start with 'scope' followed by the scope name with first letter uppercase.
When using the scope, call it without the 'scope' prefix, like Model::name($params).
Examples
This scope filters records where the 'active' column is 1.
Laravel
public function scopeActive($query)
{
return $query->where('active', 1);
}
This scope filters records by a given type passed as a parameter.
Laravel
public function scopeOfType($query, $type)
{
return $query->where('type', $type);
}
Sample Program
This example shows a User model with two query scopes: active and role. You can call these scopes to filter users easily. The example prints the SQL queries generated by these scopes.
Laravel
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
// Scope to get only active users
public function scopeActive($query)
{
return $query->where('active', 1);
}
// Scope to get users by role
public function scopeRole($query, $role)
{
return $query->where('role', $role);
}
}
// Usage example in a controller or elsewhere
$activeUsers = User::active()->get();
$adminUsers = User::role('admin')->get();
// For demonstration, we print the SQL queries generated
echo $activeUsers->toSql() . "\n";
echo $adminUsers->toSql() . "\n";
OutputSuccess
Important Notes
Query scopes keep your queries DRY (Don't Repeat Yourself).
Scopes can accept parameters to make them flexible.
Use scopes to improve readability and maintainability of your code.
Summary
Query scopes let you reuse common query parts inside your model.
Define scopes with methods starting with 'scope' and call them without that prefix.
Scopes can take parameters to customize the query.
Practice
(1/5)
1. What is the main purpose of using query scopes in a Laravel model?
easy
A. To create database migrations
B. To define database table relationships
C. To handle user authentication
D. To reuse common query filters easily across different queries
Solution
Step 1: Understand query scopes role
Query scopes allow you to write common query parts once and reuse them easily.
Step 2: Compare with other options
Defining relationships, migrations, or authentication are unrelated to query scopes.
Final Answer:
To reuse common query filters easily across different queries -> Option D
Quick Check:
Query scopes = reusable query filters [OK]
Hint: Query scopes = reusable query parts in models [OK]
Common Mistakes:
Confusing scopes with relationships
Thinking scopes create migrations
Mixing scopes with authentication logic
2. Which of the following is the correct way to define a query scope named active in a Laravel model?
easy
A. public function scopeActive($query) { return $query->where('status', 'active'); }
B. public function scopeActive() { return $this->where('status', 'active'); }
C. public function scope_active($query) { return $query->where('status', 'active'); }
D. public function active() { return $this->where('status', 'active'); }
Solution
Step 1: Recall scope method naming
Query scopes must be prefixed with 'scope' and accept $query as first parameter.
Step 2: Check method signature and body
public function scopeActive($query) { return $query->where('status', 'active'); } correctly uses 'scopeActive($query)' and returns $query with condition.
Final Answer:
public function scopeActive($query) { return $query->where('status', 'active'); } -> Option A
Quick Check:
Scope method = scope + $query param [OK]
Hint: Scope methods start with 'scope' and take $query param [OK]
Common Mistakes:
Omitting $query parameter
Using underscore in method name
Not prefixing method with 'scope'
3. Given this scope in a Laravel model:
public function scopePopular($query) {
return $query->where('votes', '>', 100);
}
What will User::popular()->get() return?
medium
A. All users regardless of votes
B. All users with votes less than or equal to 100
C. All users with votes greater than 100
D. Syntax error because scope is missing
Solution
Step 1: Understand the scope condition
The scope filters users where 'votes' is greater than 100.
Step 2: Analyze the query call
Calling User::popular()->get() applies the scope and returns matching users.
public function scopeRecent() {
return $this->orderBy('created_at', 'desc');
}
medium
A. Missing $query parameter in the scope method
B. Incorrect method name, should not start with 'scope'
C. Using orderBy inside scope is not allowed
D. Missing return type declaration
Solution
Step 1: Check scope method signature
Scope methods must accept $query as the first parameter to modify the query.
Step 2: Identify missing parameter
The method lacks the $query parameter, so it cannot modify the query builder.
Final Answer:
Missing $query parameter in the scope method -> Option A
Quick Check:
Scope method needs $query param [OK]
Hint: Scope methods always need $query parameter [OK]
Common Mistakes:
Forgetting $query parameter
Thinking orderBy is disallowed in scopes
Confusing method naming rules
5. You want to create a reusable scope activeAndRecent that returns users who are active and created within the last 30 days. Which of the following scope definitions is correct?
hard
A. public function scopeActiveAndRecent($query) {
return $query->where('status', 'active')
->orWhere('created_at', '>=', now()->subDays(30));
}
B. public function scopeActiveAndRecent($query) {
return $query->where('status', 'active')
->where('created_at', '>=', now()->subDays(30));
}
C. public function scopeActiveAndRecent() {
return $this->where('status', 'active')
->where('created_at', '>=', now()->subDays(30));
}
D. public function activeAndRecent($query) {
return $query->where('status', 'active')
->where('created_at', '>=', now()->subDays(30));
}
Solution
Step 1: Verify method signature and parameters
The scope method must be named with 'scope' prefix and accept $query parameter.
Step 2: Check query conditions logic
Use 'where' twice to combine conditions with AND logic for active status and recent date.
Step 3: Compare options
public function scopeActiveAndRecent($query) {
return $query->where('status', 'active')
->where('created_at', '>=', now()->subDays(30));
} correctly uses 'scopeActiveAndRecent($query)' and combines conditions with 'where'.
Final Answer:
public function scopeActiveAndRecent($query) {
return $query->where('status', 'active')
->where('created_at', '>=', now()->subDays(30));
} -> Option B
Quick Check:
Scope with $query and AND conditions = public function scopeActiveAndRecent($query) {
return $query->where('status', 'active')
->where('created_at', '>=', now()->subDays(30));
} [OK]
Hint: Use 'where' twice for AND, scope method needs $query [OK]
Common Mistakes:
Using orWhere instead of where for AND logic
Omitting $query parameter
Not prefixing method with 'scope'
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.