Challenge - 5 Problems
Query Scopes Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ component_behavior
intermediate2: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();
Attempts:
2 left
💡 Hint
Remember how Laravel converts boolean values in queries.
✗ Incorrect
Laravel converts boolean true to integer 1 in SQL queries. So the where clause becomes `published = 1`.
❓ state_output
intermediate2: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();
Attempts:
2 left
💡 Hint
Think about how Laravel treats integer 1 in queries.
✗ Incorrect
The scope adds a where clause filtering users where 'active' equals 1. This returns all users with active = 1.
📝 Syntax
advanced2: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.
Attempts:
2 left
💡 Hint
Local scopes must start with 'scope' and be instance methods.
✗ Incorrect
Local query scopes must be instance methods prefixed with 'scope'. Option C follows this pattern correctly.
🔧 Debug
advanced2: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();
Attempts:
2 left
💡 Hint
Check if the scope method returns the query builder.
✗ Incorrect
In Laravel, query scopes must return the query builder instance. Without returning, the filter is ignored.
🧠 Conceptual
expert2: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.
Attempts:
2 left
💡 Hint
Think about when each scope type is applied during querying.
✗ Incorrect
Global scopes are automatically applied to every query on the model. Local scopes need to be called explicitly.