🚀 Day 6 : Advanced Laravel : N+1 Queries Are Not Always What You Think

N+1 Queries Are Not Always What You Think

Your Laravel API returns 200 records.

Everything works.

But response time is 3.5 seconds.

You add:

User::with('orders')->get();

Now it takes 1.8 seconds.

Better? Yes.

Optimized? Not necessarily.

The biggest mistake developers make is assuming that eliminating N+1 queries automatically means the database is optimized.

Let's investigate what actually happens. 👇


1. Understanding the real N+1 problem

Consider:

$orders = Order::latest()->get();

foreach ($orders as $order) {
    echo $order->user->name;
}

Suppose there are 500 orders.

The application may execute:

1 query  → Fetch 500 orders
500 queries → Fetch each order's user

Total: 501 queries

This is the classic N+1 problem.

The solution:

$orders = Order::with('user')
    ->latest()
    ->get();

Now the typical query pattern becomes:

1 query → Fetch orders
1 query → Fetch related users

Total: 2 queries

But remember: the exact query count depends on relationships, constraints, nested loading, and database behavior.


2. The hidden problem: Eager loading can still be expensive

Consider:

$users = User::with([
    'orders',
    'orders.items',
    'profile',
    'permissions',
])->get();

You have eliminated many unnecessary individual queries.

But what if:

  • 10,000 users are returned?

  • Each user has 100 orders?

  • Every order has 20 items?

  • Each model contains expensive accessors?

You could still have serious memory and CPU problems.

Fewer queries do not automatically mean faster applications.

You must optimize:

  1. Query count

  2. Rows retrieved

  3. Columns retrieved

  4. Index usage

  5. PHP object hydration

  6. Memory consumption


3. Select only the columns you actually need

A common mistake:

$users = User::with('orders')->get();

This retrieves every selected column by default.

If your API only needs a few fields:

$users = User::query()
    ->select(['id', 'name', 'email'])
    ->with([
        'orders:id,user_id,total,status',
    ])
    ->get();

Notice that user_id is included in the order selection.

Why?

Because Eloquent needs the relationship's matching keys to associate the related records with their parent models.

Important: When limiting eager-loaded columns, always include the necessary primary and foreign keys.

This can significantly reduce unnecessary data transfer and model hydration.


4. The dangerous N+1 problem inside API Resources

Consider:

class UserResource extends JsonResource
{
    public function toArray($request): array
    {
        return [
            'id' => $this->id,
            'name' => $this->name,
            'orders_count' => $this->orders->count(),
        ];
    }
}

Now imagine returning 500 users.

If orders isn't already loaded, accessing it can trigger relationship queries during JSON serialization.

Your controller might look perfectly optimized while the API Resource introduces N+1 queries.

A better approach when you only need a count:

$users = User::query()
    ->withCount('orders')
    ->get();

Then:

'orders_count' => $this->orders_count,

You don't need to hydrate every order just to calculate a count.

Other useful methods include:

withExists('orders');

withSum('orders', 'total');

withAvg('reviews', 'rating');

withMax('orders', 'total');

Senior-engineer lesson: Optimize the data you need, not merely the number of SQL statements.


5. Understand EXPLAIN before adding indexes

Consider:

Order::where('status', 'completed')
    ->where('created_at', '>=', now()->subDays(30))
    ->get();

You may assume adding an index will solve the performance issue.

But which index?

First investigate the execution plan.

For MySQL:

EXPLAIN
SELECT *
FROM orders
WHERE status = 'completed'
AND created_at >= NOW() - INTERVAL 30 DAY;

For deeper analysis, MySQL 8 also supports:

EXPLAIN ANALYZE
SELECT *
FROM orders
WHERE status = 'completed'
AND created_at >= NOW() - INTERVAL 30 DAY;

Look at:

  • Access type

  • Possible keys

  • Selected key

  • Estimated rows

  • Actual execution time and rows

  • Temporary tables

  • Sorting operations

EXPLAIN ANALYZE executes the query, so use it carefully on production workloads.

The goal is to understand how the database executes the query, not blindly add indexes.


6. Composite indexes: Order matters

Suppose your query is:

SELECT *
FROM orders
WHERE user_id = 10
AND status = 'completed'
ORDER BY created_at DESC;

One possible index is:

CREATE INDEX idx_orders_user_status_created
ON orders (user_id, status, created_at);

Why use a composite index?

Because it can help the database locate matching rows using multiple columns.

But don't assume this index is universally optimal.

Index selection depends on:

  • Query patterns

  • Column cardinality

  • Data distribution

  • Sorting requirements

  • Existing indexes

  • Database engine behavior

Also remember that indexes have costs.

Every additional index consumes storage and can increase the cost of INSERT, UPDATE, and DELETE operations.


7. Use whereHas() carefully

Consider:

User::whereHas('orders', function ($query) {
    $query->where('status', 'completed');
})->get();

This asks for users who have matching orders.

It is different from:

User::with('orders')->get();

The first filters parent records based on a relationship condition.

The second loads related records.

If you need both filtering and matching relationship data, consider:

User::withWhereHas('orders', function ($query) {
    $query->where('status', 'completed');
})->get();

This avoids writing separate, potentially inconsistent relationship constraints.

Understanding the distinction between filtering and loading is essential for complex Eloquent queries.


8. Large datasets: Stop loading everything into memory

This is dangerous:

$orders = Order::all();

foreach ($orders as $order) {
    // Process order
}

If the table contains millions of rows, this can exhaust available memory.

For batch processing:

Order::query()
    ->chunkById(500, function ($orders) {
        foreach ($orders as $order) {
            // Process order
        }
    });

For sequential processing:

foreach (Order::lazyById(500) as $order) {
    // Process order
}

For large exports and background processing, consider chunking, cursor-based iteration, and queued jobs according to the workload.

The key is to avoid unnecessarily hydrating the entire dataset at once.


9. Detect N+1 queries automatically

Laravel offers several useful debugging mechanisms.

Prevent accidental lazy loading

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

Listen to executed queries

DB::listen(function ($query) {
    logger()->debug('Query executed', [
        'sql' => $query->sql,
        'time' => $query->time,
    ]);
});

Inspect cumulative query time

Laravel also supports cumulative query-time monitoring through:

DB::whenQueryingForLongerThan(
    500,
    function ($connection, $event) {
        logger()->warning(
            'Database query time threshold exceeded'
        );
    }
);

These tools help identify database bottlenecks before they become major production problems.


10. A real-world optimization checklist

Before releasing a slow Laravel endpoint, investigate:

ProblemPossible solution
N+1 queriesEager loading
Loading unnecessary columnsselect()
Relationship count onlywithCount()
Missing indexesAnalyze execution plans
Large memory usagechunkById() / lazyById()
Expensive relationship filteringwhereHas() / withWhereHas()
Repeated identical readsAppropriate caching
Slow SQL executionQuery-plan analysis

Don't optimize based on assumptions.

Measure first, identify the bottleneck, make one change, and measure again.


🧠 The senior Laravel developer mental model

Don't think:

Database Optimization = Add with()

Think:

Database Performance
       |
       |-- Query Count
       |
       |-- Query Execution Plan
       |
       |-- Index Strategy
       |
       |-- Data Volume
       |
       |-- Model Hydration
       |
       |-- Memory Consumption
       |
       |-- Serialization Cost

A fast Laravel application isn't necessarily the application with the fewest SQL queries.

It's the application that retrieves the right data, using an efficient execution strategy, with controlled resource consumption.


🔥 Advanced challenge for Laravel developers

Consider:

$users = User::with('orders')->get();

foreach ($users as $user) {
    echo $user->orders->count();
}

You have eliminated the classic N+1 query problem.

But if the application only needs the number of orders, which approach is better?

A.

User::with('orders')->get();

B.

User::withCount('orders')->get();

Explain the difference in terms of database work, model hydration, and memory consumption.

Share your answer in the comments.

Day 6/25 complete.

Tomorrow:

👉 Laravel Database Transactions & Isolation Levels — Deadlocks, Dirty Reads, Phantom Reads, and How to Build Reliable Financial Workflows.


Comments

Popular Posts

How to setup phpstorm in windows for laravel

🚀 Day 5 : Advanced Laravel : Eloquent ORM — What REALLY Happens When Database Rows Become PHP Objects?

🚀 Day 4 : Advanced Laravel Internals : Middleware Pipeline — What Happens Before AND After Your Controller?