How to Use with for Eager Loading in Laravel
In Laravel, use the
with method on Eloquent queries to eager load related models and reduce database queries. For example, User::with('posts')->get() loads users and their posts in one query.Syntax
The with method accepts one or more relationship names as strings to eager load them with the main model query.
Model::with('relation')->get(): Loads the specified relation.Model::with(['relation1', 'relation2'])->get(): Loads multiple relations.- Use dot notation for nested relations, e.g.,
with('relation.nestedRelation').
php
User::with('posts')->get(); User::with(['posts', 'comments'])->get(); User::with('posts.comments')->get();
Example
This example shows how to eager load the posts relationship when retrieving users. It reduces the number of database queries by loading users and their posts together.
php
<?php use App\Models\User; $users = User::with('posts')->get(); foreach ($users as $user) { echo $user->name . " has posts:\n"; foreach ($user->posts as $post) { echo "- " . $post->title . "\n"; } }
Output
Alice has posts:
- My first post
- Laravel tips
Bob has posts:
- Travel diary
Common Pitfalls
Common mistakes when using with include:
- Not defining the relationship method in the model, causing errors.
- Using
withbut still accessing relations lazily, which defeats eager loading. - Loading too many relations unnecessarily, which can slow down queries.
Always ensure relationships exist and only eager load what you need.
php
<?php // Wrong: Relationship method missing $users = User::with('posts')->get(); // Error if posts() not defined // Wrong: Eager loading but accessing relation incorrectly $users = User::with('posts')->get(); foreach ($users as $user) { $posts = Post::where('user_id', $user->id)->get(); // Extra queries } // Right: Access eager loaded relation directly foreach ($users as $user) { $posts = $user->posts; // No extra queries }
Quick Reference
| Usage | Description |
|---|---|
| Model::with('relation')->get() | Eager load a single relation |
| Model::with(['rel1', 'rel2'])->get() | Eager load multiple relations |
| Model::with('relation.nestedRelation')->get() | Eager load nested relations |
| $model->relation | Access eager loaded relation without extra query |
| Missing relation method | Causes errors when using with() |
Key Takeaways
Use
with to eager load relationships and reduce database queries.Always define relationship methods in your Eloquent models before eager loading.
Access eager loaded relations directly to avoid extra queries.
Avoid eager loading unnecessary relations to keep queries efficient.
Use dot notation to eager load nested relationships easily.