Home Arrow Icon Knowledge base Arrow Icon Global Arrow Icon Laravel eager loading example code
    Laravel eager loading performance optimization database queries Post model Comment model Eloquent relationships PHP


Laravel eager loading example code


Here's an example of how to use eager loading in Laravel to efficiently load related models:

Let's say we have two models, `Post` and `Comment`, with a one-to-many relationship (a post can have multiple comments).

First, define the relationship in the models:

php
// Post.php
class Post extends Model
{
    public function comments()
    {
        return $this->hasMany(Comment::class);
    }
}

// Comment.php 
class Comment extends Model
{
    public function post()
    {
        return $this->belongsTo(Post::class);
    }
}

Now, in your controller, you can eager load the comments when fetching posts:

php
// PostsController.php
public function index()
{
    $posts = Post::with('comments')->get();

    return view('posts.index', compact('posts'));
}

In the view, you can access the eager loaded comments:

html
{{-- posts/index.blade.php --}}
@foreach ($posts as $post)
    <h2>{{ $post->title }}</h2>
    
    <h3>Comments:</h3>
    <ul>
        @foreach ($post->comments as $comment)
            <li>{{ $comment->content }}</li>
        @endforeach
    </ul>
@endforeach

The key points are:

1. Define the relationship functions in the models
2. Use `with('relationName')` to eager load the relations when fetching the parent models
3. Access the eager loaded relations as properties on the parent models in the view

This will reduce the number of queries from N+1 (where N is the number of posts) to just 2 queries:

1. Fetch all posts
2. Fetch all comments for the fetched posts

Eager loading helps optimize performance by reducing the number of database queries required to load related models.

Citations:
[1] https://ashallendesign.co.uk/blog/how-to-force-eager-loading-and-prevent-n-1-issues-in-laravel
[2] https://www.itsolutionstuff.com/post/laravel-eager-loading-tutorialexample.html
[3] https://inspector.dev/save-1-2-million-queries-per-day-with-laravel-eager-loading/
[4] https://laravel.com/docs/5.2/eloquent-relationships
[5] https://stackoverflow.com/questions/38688962/laravel-eloquent-eager-loading