Performance Laravel 8 Laravel 9 Laravel 10 Laravel 11 Laravel 12

N+1 Query Problem in Laravel - How to Fix

The N+1 query problem occurs when your code executes one query to fetch records, then N additional queries to fetch related data.

The Error

Error Message
N+1 Query Detected (performance warning)

Common Causes

  1. 1 Accessing relationships in loops without eager loading
  2. 2 Not using with() for relationships
  3. 3 Lazy loading in large datasets
  4. 4 Blade views accessing relationships

Solutions

1

Use eager loading with with()

PHP
// Instead of (N+1 problem)
$posts = Post::all();
foreach ($posts as $post) {
    echo $post->author->name;
}

// Use eager loading
$posts = Post::with('author')->get();
2

Enable strict mode to catch N+1

PHP
// In AppServiceProvider boot()
use Illuminate\Database\Eloquent\Model;

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

Eager load multiple relationships

PHP
$posts = Post::with(['author', 'comments', 'tags'])->get();

// Nested eager loading
$posts = Post::with('comments.user')->get();
4

Use load() for already retrieved models

PHP
$posts = Post::all();
$posts->load('author', 'tags');

Need Help With Your Laravel Project?

I specialize in building custom Laravel applications, process automation, and SaaS development. Whether you need to eliminate repetitive tasks or build something from scratch, let's discuss your project.

Hafiz Riaz

About Hafiz

Senior Full Stack Developer. I build production software with Laravel, Filament, Vue, and AI integrations, and write about the real decisions behind shipping it.

Get in touch →

Related Errors