Challenge - 5 Problems
Eager Loading 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 eager loading code?
Given the following Eloquent query, what will be the number of queries executed when fetching posts with their comments eagerly loaded?
Post::with('comments')->get();Attempts:
2 left
💡 Hint
Eager loading loads related models in separate queries before accessing them.
✗ Incorrect
Eager loading with 'with' runs one query for the main model (posts) and one query for the related model (comments). This avoids running a query for each post's comments (which would be lazy loading).
📝 Syntax
intermediate2:00remaining
Which option correctly eager loads nested relationships in Laravel?
You want to eager load the 'comments' relationship and, within comments, the 'author' relationship. Which code snippet is correct?
Attempts:
2 left
💡 Hint
Use dot notation to eager load nested relationships.
✗ Incorrect
The correct syntax to eager load nested relationships is to use dot notation inside the 'with' method as a string or array.
🔧 Debug
advanced2:00remaining
Why does this eager loading code cause an error?
Consider this code:
What is the cause of the error if 'comments' is not a defined relationship on Post?
Post::with(['comments' => function($query) { $query->where('approved', true); }])->get();What is the cause of the error if 'comments' is not a defined relationship on Post?
Attempts:
2 left
💡 Hint
Check if the relationship method exists on the model.
✗ Incorrect
Eager loading requires the relationship method to be defined on the model. If 'comments' is missing, Laravel throws an error.
❓ state_output
advanced2:00remaining
What is the output count of comments when eager loading with a constraint?
Given this code:
What does
$posts = Post::with(['comments' => fn($q) => $q->where('approved', true)])->get();
$count = $posts->first()->comments->count();What does
$count represent?Attempts:
2 left
💡 Hint
Eager loading constraints filter the related models loaded.
✗ Incorrect
The closure inside 'with' filters comments to only those approved, so the comments collection contains only approved comments.
🧠 Conceptual
expert2:00remaining
Why prefer eager loading over lazy loading in Laravel?
Which is the main reason to use eager loading (with) instead of lazy loading when fetching related models in Laravel?
Attempts:
2 left
💡 Hint
Think about how many queries run when accessing related data.
✗ Incorrect
Eager loading reduces the number of queries by loading related data in fewer queries, avoiding the N+1 query problem.