Bird
Raised Fist0
Laravelframework~20 mins

Eager loading (with) in Laravel - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Eager Loading 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 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();
A1 query executed: one for posts and their comments together
B2 queries executed: one for posts and one for comments
CMultiple queries executed: one for each post's comments
DNo queries executed until comments are accessed
Attempts:
2 left
💡 Hint
Eager loading loads related models in separate queries before accessing them.
📝 Syntax
intermediate
2: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?
APost::with('comments->author')->get();
BPost::with(['comments', 'author'])->get();
CPost::with('comments.author')->get();
DPost::with('comments')->with('author')->get();
Attempts:
2 left
💡 Hint
Use dot notation to eager load nested relationships.
🔧 Debug
advanced
2:00remaining
Why does this eager loading code cause an error?
Consider this code:

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?
AThe 'approved' column does not exist in the comments table, causing a database error.
BThe closure syntax inside 'with' is invalid and causes a syntax error.
CThe 'where' clause inside the closure is not allowed in eager loading.
DThe 'comments' relationship is not defined on the Post model, causing a runtime error.
Attempts:
2 left
💡 Hint
Check if the relationship method exists on the model.
❓ state_output
advanced
2:00remaining
What is the output count of comments when eager loading with a constraint?
Given this code:

$posts = Post::with(['comments' => fn($q) => $q->where('approved', true)])->get();
$count = $posts->first()->comments->count();


What does $count represent?
AThe number of approved comments for the first post
BThe total number of comments for all posts
CThe total number of comments for the first post, ignoring approval
DAlways zero because eager loading with constraints disables comments
Attempts:
2 left
💡 Hint
Eager loading constraints filter the related models loaded.
🧠 Conceptual
expert
2: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?
ATo reduce the number of database queries and improve performance
BTo load related models only when accessed to save memory
CTo automatically cache related models for offline use
DTo force Laravel to use raw SQL queries instead of Eloquent
Attempts:
2 left
💡 Hint
Think about how many queries run when accessing related data.

Practice

(1/5)
1. What is the main purpose of using with() in Laravel Eloquent queries?
easy
A. To delete related models automatically
B. To load related models in the same query to reduce database calls
C. To paginate the results of a query
D. To sort the results by a related model's attribute

Solution

  1. Step 1: Understand what with() does

    The with() method tells Laravel to load related models eagerly, meaning it fetches them in the same database query or fewer queries.
  2. Step 2: Identify the benefit of eager loading

    This reduces the number of database queries, improving performance by avoiding the N+1 query problem.
  3. Final Answer:

    To load related models in the same query to reduce database calls -> Option B
  4. Quick Check:

    Eager loading = fewer queries = better performance [OK]
Hint: Remember: with() loads related data upfront [OK]
Common Mistakes:
  • Thinking with() deletes related data
  • Confusing with() with pagination
  • Assuming with() sorts results
2. Which of the following is the correct syntax to eager load the 'comments' relationship on a Post model?
easy
A. Post::with('comments')->get();
B. Post::fetch('comments')->all();
C. Post::eager('comments')->all();
D. Post::load('comments')->get();

Solution

  1. Step 1: Recall the correct method for eager loading

    Laravel uses the with() method to eager load relationships before fetching results.
  2. Step 2: Check the syntax correctness

    Post::with('comments')->get(); correctly calls with() and then get() to retrieve posts with comments.
  3. Final Answer:

    Post::with('comments')->get(); -> Option A
  4. Quick Check:

    with() + get() = eager load [OK]
Hint: Use with() before get() to eager load [OK]
Common Mistakes:
  • Using load() statically instead of on model instance
  • Using non-existent methods like eager() or fetch()
  • Calling get() before with()
3. Given the code:
 $users = User::with('posts')->get();
foreach ($users as $user) {
echo $user->posts->count();
}

What will this code output?
medium
A. An error because posts is not loaded
B. The total number of users instead of posts
C. Always zero because posts are not counted
D. The number of posts for each user without extra queries

Solution

  1. Step 1: Understand eager loading effect

    The with('posts') loads all posts for each user in one query, so $user->posts is available without extra queries.
  2. Step 2: Analyze the loop output

    For each user, $user->posts->count() returns the number of posts related to that user, printed one by one.
  3. Final Answer:

    The number of posts for each user without extra queries -> Option D
  4. Quick Check:

    with() loads posts, count() shows posts per user [OK]
Hint: with() loads related data, so count() works without errors [OK]
Common Mistakes:
  • Assuming posts are not loaded and cause errors
  • Thinking count() returns total users
  • Confusing eager loading with lazy loading
4. Identify the error in this code snippet:
$orders = Order::with('customer')->get();
foreach ($orders as $order) {
echo $order->customer->name;
}

Assuming the 'customer' relation is defined correctly, what is the likely problem?
medium
A. Using with() after get() instead of before
B. Missing parentheses on customer relation call
C. Accessing customer without checking if it exists
D. Using get() instead of first()

Solution

  1. Step 1: Check eager loading usage

    The with('customer') is correctly used before get(), so related customers are loaded.
  2. Step 2: Identify potential null relation access

    Some orders might not have a customer, so $order->customer could be null, causing an error when accessing name without a check.
  3. Final Answer:

    Accessing customer without checking if it exists -> Option C
  4. Quick Check:

    Null relation access causes error, check before use [OK]
Hint: Always check if related model exists before accessing properties [OK]
Common Mistakes:
  • Thinking with() must come after get()
  • Assuming relation always exists
  • Confusing get() and first() usage
5. You want to eager load the 'comments' and their 'author' for each post efficiently. Which code correctly achieves this?
hard
A. Post::with(['comments.author'])->get();
B. Post::load('comments.author')->get();
C. Post::with(['comments', 'author'])->get();
D. Post::with('comments', 'author')->get();

Solution

  1. Step 1: Understand nested eager loading syntax

    To eager load a relation of a relation, use dot notation inside an array: with(['comments.author']).
  2. Step 2: Analyze each option

    Post::with('comments', 'author')->get(); loads comments and author separately, but author is not a direct relation of Post. Post::load('comments.author')->get(); uses load() statically, which is invalid as load() is an instance method. Post::with(['comments', 'author'])->get(); loads comments and author separately as array elements, but author is not direct relation. Post::with(['comments.author'])->get(); correctly loads comments and their author nested.
  3. Final Answer:

    Post::with(['comments.author'])->get(); -> Option A
  4. Quick Check:

    Nested relations use dot notation inside array [OK]
Hint: Use dot notation inside array for nested eager loading [OK]
Common Mistakes:
  • Passing multiple relations as separate strings without array
  • Using load() statically
  • Trying to load unrelated models directly
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