🔴 Laravel Intermediate

What is the N+1 problem and how does eager loading solve it?

Why Interviewers Ask This

Candidates at the intermediate level are expected to not only know this concept but explain the trade-offs involved. Interviewers use this question to see if you can reason about design decisions, not just recall facts.

Answer

The N+1 query problem occurs when loading a collection of models and then accessing a relationship on each one, triggering one query to load the collection and then N additional queries (one per model) to load the relationship. Example: $posts = Post::all(); (1 query) then foreach ($posts as $post) { echo $post->user->name; } executes one query per post. For 100 posts, that is 101 queries. Eager loading solves this with the with() method: $posts = Post::with("user")->get(); — this executes exactly 2 queries total (one for posts, one for all their users). Load multiple: with(["user", "tags", "comments"]). Nested eager loading: with("comments.author"). Use withCount() to load relationship counts without loading the related models.

Pro Tip

If you're unsure about a detail, say so honestly and explain your reasoning. Interviewers respect candidates who can think through uncertainty rather than bluffing.