Bird
Raised Fist0
Laravelframework~10 mins

Eager loading (with) in Laravel - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Eager loading (with)
Start Query
↓
Specify Relations with with()
↓
Build SQL for Main Model
↓
Build SQL for Related Models
↓
Execute Queries
↓
Combine Results
↓
Return Models with Relations Loaded
This flow shows how Laravel builds and executes queries to load main models and their related models together using eager loading.
Execution Sample
Laravel
User::with('posts')->get();
This code loads all users and their related posts in one go to avoid extra queries later.
Execution Table
StepActionQuery BuiltResultNotes
1Start query for User modelSELECT * FROM usersAll users fetchedMain model query prepared
2Identify relation 'posts'SELECT * FROM posts WHERE user_id IN (user ids)Posts for all users fetchedRelated model query prepared
3Combine users and postsN/AUsers with posts attachedEager loading combines data
4Return resultN/ACollection of users with postsReady for use without extra queries
5EndN/AQuery completeNo lazy loading needed
💡 All related posts loaded with users, avoiding multiple queries per user.
Variable Tracker
VariableStartAfter Step 1After Step 2After Step 3Final
usersemptyall users from DBall users from DBusers with posts attachedusers with posts attached
postsemptyemptyall posts for usersall posts for usersall posts for users
Key Moments - 2 Insights
Why does Laravel run two queries instead of one when using with('posts')?
Laravel runs one query for users and one for posts with a WHERE IN clause to efficiently load all related posts at once, as shown in execution_table rows 1 and 2.
What happens if we don't use with() and access posts later?
Without with(), Laravel runs a new query for posts each time you access posts on a user, causing many queries. Eager loading avoids this by loading all posts upfront (see execution_table row 5).
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what query is built at step 2?
ASELECT * FROM users
BSELECT * FROM posts
CSELECT * FROM posts WHERE user_id IN (user ids)
DSELECT * FROM users WHERE id IN (post ids)
💡 Hint
Check the 'Query Built' column in row 2 of the execution_table.
At which step are users combined with their posts?
AStep 3
BStep 2
CStep 1
DStep 4
💡 Hint
Look at the 'Action' column describing combining results in the execution_table.
If we remove with('posts'), how would the variable 'posts' change after step 2?
AIt would contain all posts for users
BIt would remain empty
CIt would contain posts for only one user
DIt would cause an error
💡 Hint
Refer to variable_tracker row for 'posts' and understand eager loading effect.
Concept Snapshot
Eager loading with with() loads related models in advance.
Syntax: Model::with('relation')->get();
Runs separate queries for main and related models.
Combines results to avoid many queries later.
Improves performance by reducing database calls.
Full Transcript
Eager loading in Laravel uses the with() method to load related models together with the main model. When you call User::with('posts')->get(), Laravel builds one query to get all users and another query to get all posts for those users using a WHERE IN clause. Then it combines the posts with their respective users before returning the result. This avoids running a new query for posts each time you access them on a user, which would happen without eager loading. The process involves starting the main query, preparing the related query, executing both, and combining the data. This makes your app faster and more efficient by reducing the number of database queries.

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