The N+1 Problem & Eager Loading — Database

N+1 happens when 1 query fetches a list, then the code sends 1 more query for each item's relation: 10 orders become 11 queries, 1,000 become 1,001. The…

You need 10 things from the corner shop. Instead of one trip, you walk there and back 10 times, one item per trip. The items aren't heavy. The trips are what make you tired.

Code can do the same to a database. In this picture, the shop is the database and the items are the data you fetch. The problem is called the N+1 problem: code fetches a list with 1 query, then sends 1 more query for every item in that list. N items means N + 1 queries in total. Every query is one round trip from the app to the database and back.

The tables we're using

We continue with Sunset Coffee. Its customers are Budi (id 1), Siti (2) and Andi (3). The orders table already holds 20 orders, and each one points at its customer through customer_id:

CREATE TABLE customers (id INTEGER PRIMARY KEY, name TEXT NOT NULL);
CREATE TABLE orders (
  id INTEGER PRIMARY KEY,
  customer_id INTEGER NOT NULL REFERENCES customers(id),
  total INTEGER NOT NULL  -- in cents
);

In Laravel, code reads tables through Eloquent, Laravel's built-in ORM. An ORM is a library that turns table rows into PHP objects and writes the SQL for you. Each table has one model (a PHP class): Order for orders. The Order model has a customer relation: one order belongs to one customer.

class Order extends Model
{
    public function customer(): BelongsTo
    {
        return $this->belongsTo(Customer::class);
    }
}

belongsTo(Customer::class) means customer_id points at one row in customers (the Customer model).

One query per order

The admin page "Newest orders" shows 10 orders with their customers' names:

$orders = Order::orderByDesc('id')->take(10)->get();

foreach ($orders as $order) {
    echo $order->customer->name; // a new query here, on every pass
}

orderByDesc('id')->take(10)->get() is how Eloquent writes ORDER BY id DESC LIMIT 10. Before you look at the query log (a record of every query the app sends), try to count. How many queries does the code above, with $order->customer->name inside the loop, send to the database: 1, 2, or 11?

These are the queries that actually reach the database, exactly as Laravel's query log shows them:

SELECT * FROM orders ORDER BY id DESC LIMIT 10;
SELECT * FROM customers WHERE id = 2 LIMIT 1;  -- order #20, Siti
SELECT * FROM customers WHERE id = 1 LIMIT 1;  -- order #19, Budi
SELECT * FROM customers WHERE id = 2 LIMIT 1;  -- order #18, Siti again
SELECT * FROM customers WHERE id = 3 LIMIT 1;  -- order #17, Andi
-- ... 6 more queries, one per order

That's 11 queries: 1 for the list of orders, plus 10 for customers, one per order.

The more orders on the page, the more queries: 100 orders become 101 queries, 1,000 become 1,001. On your laptop, with 3 orders, everything feels fast. In production the database usually sits on another server. So every query crosses the network, and that takes, for example, 0.5 to 1 ms, even when both servers are in the same data centre. 1,001 queries means half a second to a second spent on round trips alone.

Eager loading with with()

The fix: tell Eloquent at the start that the customer relation will be used.

$orders = Order::with('customer')->orderByDesc('id')->take(10)->get();

foreach ($orders as $order) {
    echo $order->customer->name; // already in memory, no query
}

The query log now holds only two queries:

SELECT * FROM orders ORDER BY id DESC LIMIT 10;
SELECT * FROM customers WHERE id IN (1, 2, 3);

Loading a relation up front, together with the main query, is called eager loading. The result is always 2 queries for one relation, however many orders there are:

Number of orders Lazy loading Eager loading with()
10 11 queries 2 queries
100 101 queries 2 queries
1,000 1,001 queries 2 queries

Two relations, for example with('customer', 'items'), means 3 queries: 1 for the orders, plus 1 per relation. The items relation holds the product lines of each order.

How to spot N+1

public function boot(): void
{
    Model::preventLazyLoading(! $this->app->isProduction());
}

! $this->app->isProduction() means "not in production". So on your laptop, the code with 10 orders above now stops with LazyLoadingViolationException: Attempted to lazy load [customer] on model [App\Models\Order] but lazy loading is disabled. In production, the app keeps running as usual. The exception: when a query returns just one row, lazy loading on that one model is still allowed, because one model alone can't cause N+1.

N+1 isn't only a Laravel thing. In JavaScript, without an ORM, it has the same shape: for (const order of orders) { await db.query('SELECT * FROM customers WHERE id = ?', [order.customer_id]) } is 1 + N queries too.

📌 withCount and nested relations

⚠️ N+1 that your checks miss

TL;DR: N+1 happens when 1 query fetches a list, then the code sends 1 more query for each item's relation: 10 orders become 11 queries, 1,000 become 1,001. The cause: Eloquent (Laravel's ORM, a library that writes the SQL for you) uses lazy loading: a relation is only fetched when it's accessed. Eager loading with Order::with('customer') loads the relation up front through one WHERE id IN (...), so the total is always 2 queries for one relation. Check the query count in the query log (a record of the queries the app sends) or Laravel Debugbar. Also turn on Model::preventLazyLoading() in development, so the code stops with an error whenever lazy loading happens, and N+1 shows up right away.

⚡ One query per order

Write:

$orders = Order::orderByDesc('id')->take(10)->get();

foreach ($orders as $order) {
    echo $order->customer->name; // a new query here, on every pass
}
Guess first: this code fetches 10 orders, then reads each order's customer name. How many queries does it send to the database: 1, 2, or 11?

The answer is 11. One for the list of orders, plus 10 for customers, one per order.

Meaning: N+1 means 1 query for the list, then N extra queries for each item's relation (here, each order's customer). Eloquent, Laravel's ORM (a library that writes the SQL for you), uses lazy loading: a relation is only fetched when it's accessed. So 100 orders become 101 queries.

⚡ Eager loading with with()

Write:

$orders = Order::with('customer')->orderByDesc('id')->take(10)->get();

Meaning: with('customer') loads the relation up front. Laravel collects the customer_id of every order, then fetches all their customers through one WHERE id IN (...). This is called eager loading. The total is always 2 queries for one relation, however many orders there are.

In the exercise, eager loading stays at 2 queries: countQueries(1000, true) returns 2, not 1001.

⚡ Catch it early

Write:

Model::preventLazyLoading(! $this->app->isProduction());

Meaning: ! $this->app->isProduction() means "not in production". So in development (while you try the code on your laptop), the code stops with an error as soon as lazy loading happens, and N+1 is caught before it reaches production.

What you will learn