As you might have used **Eloquent **in all of your **Laravel **projects you feel the comfort the Eloquent brings to your life.

Eloquent is saving tons of time from developers, but it can run into issues if you don’t take care of the queries. One of the problems that can happen is known as the N+1 problem.

What is the N+1 problem?

Let’s explain it in practice:

Suppose you have two models called User and Post.

Post model

Post model

s

User model

As you can see a user can have many posts and a post is written by a user (author).


Now we’re going to have a list of all posts with their authors’ names next to them.

  1. We should have a route to see the page:

routes/web.php file

routes/web.php file

2. In the controller we have to retrieve all of the posts from the database:

PostController.php file

#mysql #programming #laravel #database #php

Avoid N+1 problem using Eloquent ORM
1.30 GEEK