0
0
Laravelframework~30 mins

Eager loading (with) in Laravel - Mini Project: Build & Apply

Choose your learning style9 modes available
Eager Loading with Laravel
📖 Scenario: You are building a simple blog application using Laravel. Each blog post has an author and multiple comments. To improve performance, you want to load the posts along with their authors and comments in one query.
🎯 Goal: Build a Laravel query that uses eager loading with with to load posts together with their related authors and comments.
📋 What You'll Learn
Create a Post model instance query
Add eager loading for the author relationship
Add eager loading for the comments relationship
Retrieve all posts with their authors and comments in one query
💡 Why This Matters
🌍 Real World
Eager loading helps reduce the number of database queries when loading related data, making web applications faster and more efficient.
💼 Career
Understanding eager loading is essential for Laravel developers to write performant database queries and build scalable applications.
Progress0 / 4 steps
1
Create the base query for posts
Create a variable called posts and assign it the query builder for the Post model using Post::query().
Laravel
Need a hint?

Use Post::query() to start building a query for posts.

2
Add eager loading for the author relationship
Add eager loading for the author relationship to the $posts query using the with method.
Laravel
Need a hint?

Use with('author') to eager load the author relationship.

3
Add eager loading for the comments relationship
Extend the $posts query to eager load both author and comments relationships by passing an array to the with method.
Laravel
Need a hint?

Pass an array ['author', 'comments'] to with to eager load both relationships.

4
Retrieve all posts with eager loaded relationships
Complete the query by calling get() on $posts to retrieve all posts with their authors and comments.
Laravel
Need a hint?

Call get() to execute the query and get the results.