Eager loading helps you get related data from the database all at once. This makes your app faster by avoiding many small database calls.
0
0
Eager loading (with) in Laravel
Introduction
When you want to show a list of posts with their authors without slowing down your app.
When you need to display products with their categories in one page.
When you want to load comments for many articles efficiently.
When you want to avoid the 'N+1 query problem' in your database queries.
Syntax
Laravel
Model::with('relation')->get();
Replace 'Model' with your main model name.
Replace 'relation' with the name of the related model method defined in your model.
Examples
Loads all posts with their related author data in one query.
Laravel
Post::with('author')->get();
Loads products with both category and supplier data eagerly.
Laravel
Product::with(['category', 'supplier'])->get();
Loads users with their roles and each role's permissions in nested eager loading.
Laravel
User::with('roles.permissions')->get();
Sample Program
This code loads all posts with their authors in one query. Then it prints each post's title and the author's name.
Laravel
<?php use App\Models\Post; $posts = Post::with('author')->get(); foreach ($posts as $post) { echo "Title: {$post->title}\n"; echo "Author: {$post->author->name}\n\n"; }
OutputSuccess
Important Notes
Make sure the relation method (like author()) is defined in your model.
Eager loading reduces database queries, improving performance.
You can eager load nested relations by using dot notation like 'roles.permissions'.
Summary
Eager loading fetches related data in one go to speed up your app.
Use with() method with the relation name to load related models.
This helps avoid many small database queries and improves performance.