Bird
Raised Fist0
Laravelframework~20 mins

Query scopes in Laravel - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Query Scopes Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ component_behavior
intermediate
2:00remaining
What is the output of this Laravel query scope usage?
Given the following Laravel model and query, what will be the SQL query generated and executed?
Laravel
class Post extends Model {
    public function scopePublished($query) {
        return $query->where('published', true);
    }
}

$posts = Post::published()->toSql();
A"select * from `posts` where `published` = 1"
B"select * from `posts` where `published` = true"
C"select * from `posts` where `published` = 'true'"
D"select * from `posts` where `published` = '1'"
Attempts:
2 left
💡 Hint
Remember how Laravel converts boolean values in queries.
❓ state_output
intermediate
2:00remaining
What is the value of $users after applying this scope?
Consider this Laravel model and query. What users will be included in $users?
Laravel
class User extends Model {
    public function scopeActive($query) {
        return $query->where('active', 1);
    }
}

$users = User::active()->get();
ANo users, because scope is not applied correctly
BAll users with 'active' column set to true (boolean)
CAll users regardless of 'active' status
DAll users with 'active' column set to 1
Attempts:
2 left
💡 Hint
Think about how Laravel treats integer 1 in queries.
📝 Syntax
advanced
2:00remaining
Which option correctly defines a local query scope in Laravel?
Choose the correct syntax for defining a local query scope named 'recent' in a Laravel model.
Apublic static function scopeRecent($query) { return $query->orderBy('created_at', 'desc'); }
Bpublic function recent($query) { return $query->orderBy('created_at', 'desc'); }
Cpublic function scopeRecent($query) { return $query->orderBy('created_at', 'desc'); }
Dpublic function recentScope($query) { return $query->orderBy('created_at', 'desc'); }
Attempts:
2 left
💡 Hint
Local scopes must start with 'scope' and be instance methods.
🔧 Debug
advanced
2:00remaining
Why does this query scope not filter results as expected?
Given this scope and usage, why does the query return all records instead of filtered ones?
Laravel
class Product extends Model {
    public function scopeInStock($query) {
        $query->where('stock', '>', 0);
    }
}

$products = Product::inStock()->get();
AThe query builder does not support where clauses in scopes.
BThe scope method does not return the query, so the filter is not applied.
CThe scope method should be static to work properly.
DThe where clause is incorrect; it should be 'stock' >= 1.
Attempts:
2 left
💡 Hint
Check if the scope method returns the query builder.
🧠 Conceptual
expert
2:00remaining
How do global query scopes differ from local query scopes in Laravel?
Select the statement that correctly describes the difference between global and local query scopes.
AGlobal scopes automatically apply to all queries on the model, while local scopes must be explicitly called.
BLocal scopes apply to all queries automatically, but global scopes require manual invocation.
CGlobal scopes can only filter by one column, local scopes can filter by multiple columns.
DLocal scopes are defined in service providers, global scopes inside models.
Attempts:
2 left
💡 Hint
Think about when each scope type is applied during querying.

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

  1. Step 1: Understand query scopes role

    Query scopes allow you to write common query parts once and reuse them easily.
  2. Step 2: Compare with other options

    Defining relationships, migrations, or authentication are unrelated to query scopes.
  3. Final Answer:

    To reuse common query filters easily across different queries -> Option D
  4. 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

  1. Step 1: Recall scope method naming

    Query scopes must be prefixed with 'scope' and accept $query as first parameter.
  2. 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.
  3. Final Answer:

    public function scopeActive($query) { return $query->where('status', 'active'); } -> Option A
  4. 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

  1. Step 1: Understand the scope condition

    The scope filters users where 'votes' is greater than 100.
  2. Step 2: Analyze the query call

    Calling User::popular()->get() applies the scope and returns matching users.
  3. Final Answer:

    All users with votes greater than 100 -> Option C
  4. Quick Check:

    Scope filters votes > 100 = users returned [OK]
Hint: Scope filters queries; check condition carefully [OK]
Common Mistakes:
  • Confusing greater than with less than
  • Assuming scope returns all records
  • Thinking scope causes syntax error
4. Identify the error in this scope definition:
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

  1. Step 1: Check scope method signature

    Scope methods must accept $query as the first parameter to modify the query.
  2. Step 2: Identify missing parameter

    The method lacks the $query parameter, so it cannot modify the query builder.
  3. Final Answer:

    Missing $query parameter in the scope method -> Option A
  4. 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

  1. Step 1: Verify method signature and parameters

    The scope method must be named with 'scope' prefix and accept $query parameter.
  2. Step 2: Check query conditions logic

    Use 'where' twice to combine conditions with AND logic for active status and recent date.
  3. 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'.
  4. Final Answer:

    public function scopeActiveAndRecent($query) { return $query->where('status', 'active') ->where('created_at', '>=', now()->subDays(30)); } -> Option B
  5. 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 unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard