Laravel

Fix Laravel N+1 queries: lazy loading vs eager loading

Understand Laravel N+1 queries with matching Eloquent examples, explicit eager loading, relationship counts and a practical query-measurement checklist.

A project list looks fast with three records. Later, its response time rises as the list grows. One possible cause is an N+1 query pattern: the application fetches a collection, then fetches related data separately while looping over it.

This walkthrough uses an existing Project model with an owner() belongs-to relationship. It illustrates query behavior; the counts below are expectations under stated assumptions, not benchmark results from a deployed application.

Without explicit eager loading

Assume relationship autoloading is disabled, no relationships were already loaded, and each project references a distinct owner:

$projects = Project::query()->limit(20)->get();

foreach ($projects as $project) {
    echo $project->owner?->name;
}

Accessing owner can issue another query for each model. For twenty projects, that can mean one project query plus twenty owner queries. Authentication, middleware and other application work can add more queries to the request.

The issue can also be hidden inside a Blade template, an accessor or an API resource. The controller’s initial query is only the beginning of what the request executes.

With explicit eager loading

Request the relationship before iterating:

$projects = Project::query()
    ->with('owner')
    ->limit(20)
    ->get();

foreach ($projects as $project) {
    echo $project->owner?->name;
}

For this simple belongs-to example, Eloquent can fetch the owners together instead of issuing one query per project. With matching owner records, expect two queries for this portion of the request. See Laravel’s official relationship documentation.

In a real endpoint, preserve your existing tenant or account scope. Eager loading is a performance decision, not permission enforcement. Escape output through the relevant template system rather than copying raw echo statements into public views.

Load the information the page actually uses

If a card displays an owner name, loading every owner’s large profile payload is unnecessary. Select the required columns, retaining keys needed to match records:

$projects = Project::query()
    ->select(['id', 'name', 'owner_id'])
    ->with('owner:id,name')
    ->limit(20)
    ->get();

If the page only displays a task count, consider withCount('tasks') instead of loading all task models. Check the actual relationship and generated query before applying that change.

Calling a relationship method such as tasks()->count() inside each iteration can still execute repeated queries, even if other relationships were eager loaded. Inspect the full rendering path.

Detect regressions during development

Laravel supports preventing accidental lazy loading. Add this to the existing boot() method of your application’s provider, preserving its other setup:

use Illuminate\Database\Eloquent\Model;

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

Verify the behavior with your application’s lazy-loading configuration. A guard helps identify missing relationships while developing; it does not automatically choose the best query or assess memory usage.

Measure before claiming an improvement

Use a local profiler or scoped query instrumentation with representative test data. Compare the same endpoint, account and record set. Record query count, repeated query shapes, response time and memory use.

Observation Investigation
Similar owner queries repeat for every row Check missing eager loading
Query count is low but response is slow Inspect query plans, indexes and other request work
Memory rises after eager loading Check collection size and unnecessary relationships
Only one API response is slow Inspect its resource transformation and accessors

Do not write a test asserting the total query count of the entire application unless that number represents a stable requirement. Prefer a targeted regression check around the affected path with enough records to expose the pattern.

For the surrounding interface, see Livewire vs Inertia dashboards. When the slow work belongs outside the request entirely, first understand how to diagnose Laravel queue processing.