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 (usingWHERE IN).$posts->load('author')eager-loads after the fact;loadMissingonly loads what is not loaded yet.withCount('comments'),withSum,withExistsadd 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).
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
- Gates or policies: how does authorization work in Laravel?
- How do queues work in Laravel?
- How do database transactions work in Laravel, and what pitfalls should you know?
- How do you validate requests in Laravel? Why use Form Requests?
- Which Artisan commands would you run when deploying Laravel to production, and why?
- What is the service container, and how does dependency injection work in Laravel?
- What is mass assignment, and how do $fillable and $guarded protect against it?
- A Laravel endpoint is slow. How do you find and fix the cause?