0
0
Laravelframework~10 mins

Lazy loading and N+1 prevention in Laravel - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to eager load the 'posts' relationship for all users.

Laravel
$users = User::[1]('posts')->get();
Drag options to blanks, or click blank then click option'
Awith
Bload
Cselect
Dfind
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'load' instead of 'with' on the query builder causes errors.
Using 'select' only chooses columns, not relationships.
2fill in blank
medium

Complete the code to lazy load the 'comments' relationship on an existing $post model.

Laravel
$post->[1]('comments');
Drag options to blanks, or click blank then click option'
Aload
Bwith
CeagerLoad
Dfetch
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'with' on a model instance instead of a query builder.
Using non-existent methods like 'eagerLoad' or 'fetch'.
3fill in blank
hard

Fix the error in the code to prevent N+1 queries when accessing each user's posts count.

Laravel
foreach ($users as $user) {
    echo $user->posts->count();
}

// Fix by eager loading posts count:
$users = User::[1]('posts')->get();
Drag options to blanks, or click blank then click option'
AloadCount
BwithCount
CcountWith
DwithPostsCount
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'loadCount' which is a method on model instances, not query builder.
Using made-up methods like 'countWith' or 'withPostsCount'.
4fill in blank
hard

Fill both blanks to eager load 'comments' and 'author' relationships for posts.

Laravel
$posts = Post::[1](['comments', [2]])->get();
Drag options to blanks, or click blank then click option'
Awith
Bload
C'author'
D'user'
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'load' instead of 'with' on the query builder.
Using 'user' instead of 'author' if the relationship is named 'author'.
5fill in blank
hard

Fill all three blanks to eager load 'tags', count 'comments', and filter posts with more than 5 comments.

Laravel
$posts = Post::[1]('tags')->[2]('comments')->having('[3]', '>', 5)->get();
Drag options to blanks, or click blank then click option'
Awith
BwithCount
Ccomments_count
Dload
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'load' instead of 'with' on the query builder.
Using 'comments' instead of 'comments_count' in having clause.