Posts Learn Components Snippets Categories Tags Tools About
/

How to Eager Loading in Laravel 8

Learn to eager loading to prevent N+1 problem and improve the speed of your query.

Created on Jun 26, 2021

388 views

Eager loading in Laravel is very simple and it can help you to prevent the N+1 problem with your data. The way how it solves is by only querying the main table once and then another one to get the table relationship.

Using "With" Method
Imagine having a "post" controller and you want to eager load the "comments" relation. You can achieve it like below.
# app/Http/Controllers/PostController.php

public function show(int $postId)
{
    $postWithComments = Post::with('comments')->findOrFail($postId);

    dd($postWithComments);
}

Using "Load" Method
Or if you are using route model binding then you can make use of the "load" method of the model instance.
# app/Http/Controllers/PostController.php

public function show(Post $post)
{
    $postWithComments = $post->load('comments');

    dd($postWithComments);
}

Nested Relation
If you have a nested relation then you can make use of the "dot" character to call the nested relationship. For example "post" has many "comments" and each of the comments has many "likes" then you can define it like below
# app/Http/Controllers/PostController.php

public function show(Post $post)
{
    $postWithCommentsAndLikes = $post->load('comments.likes');

    dd($postWithComments);
}

If you like our tutorial, do make sure to support us by being our Patreon or buy us some coffee ☕️

Load comments for How to Eager Loading in Laravel 8

)