Home / Snippets / How to Eager Loading in Laravel 8
How to Eager Loading in Laravel 8 cover

How to Eager Loading in Laravel 8

369

2 years ago

0 comments

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);
}
notion avatar

Ahmad Aziz

Week-end developer currently experimenting with web, mobile, and all things programming.

Topics:

Frontend

Resource

Average

Average

Support Us

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

Post Tutorials

Learn trending tutorials for ReactJs, React Native, VueJS, NextJs, Laravel, Tailwind CSS, and Flutter development.
View Tutorials

Code Components

Collection of Tailwind CSS components for everyone to use. Browse all of the components that's right for your web projects
View Components

Welcome to PostSrc V3

PostSrc Dark Logo

You have to login to favorite this