Laravel interview question · Most asked

What is the N+1 query problem in Eloquent and how do you prevent it?

Summary

N+1 happens when you load a list of models (1 query) and then access a relationship on each one, which lazy-loads it with one more query per model (N queries). Fix it with eager loading: with(), load() or withCount().

Longer Answer

Post::all() followed by $post->author->name in a loop runs one query for posts and one per post for authors. With 500 posts that is 501 queries; locally it feels fine, in production it is slow.

  • Post::with('author', 'comments.user')->get() loads relationships in one query each (using WHERE IN).
  • $posts->load('author') eager-loads after the fact; loadMissing only loads what is not loaded yet.
  • withCount('comments'), withSum, withExists add aggregates without loading the related rows.
  • Constrain eager loads: with(['comments' => fn ($q) => $q->latest()->limit(5)]).

To catch it early, call Model::preventLazyLoading(! app()->isProduction()) in a service provider, so lazy loading throws in development and tests. Laravel Debugbar or Telescope show query counts per request.

Code Example

// N+1: one query per order for items, and one per item for its product
$orders = Order::where('customer_id', $id)->get();

// Eager loaded: 3 queries in total
$orders = Order::with('items.product')->where('customer_id', $id)->get();

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

Key Points

  • One query for the list plus one per row.
  • with, load, loadMissing, withCount.
  • Model::preventLazyLoading() in non-production.
  • Measure query counts (Debugbar, Telescope).

Deep dive: Code Clinic: review a Laravel orders controller

Explanation

What interviewers look for

This is the most common Laravel interview question. Strong answers include how to detect N+1 automatically, not just how to fix one instance.

Follow-up questions

  • What does eager loading do in SQL?
  • How would you eager load only the latest comment per post?

More most-asked Laravel questions

← All Laravel questions