PHP 8 interview question · Most asked

What is the N+1 query problem and how do you fix it in PHP ORMs?

Summary

N+1 happens when you load N records and then lazily query a relation for each one, producing N extra queries. Fix it with eager loading (with() in Eloquent, JOIN FETCH/addSelect in Doctrine) or batched queries.

Longer Answer

Example: listing 50 posts and calling $post->author->name triggers 51 queries. In Laravel use Post::with('author')->get(); enable Model::preventLazyLoading() in development to catch it. In Doctrine, use DQL with JOIN ... SELECT or batch fetching. Tools: Laravel Debugbar, Symfony Profiler, query logs.

Key Points

  • Eager load relations you will access
  • Detect with profiler or preventLazyLoading()
  • Select only needed columns
  • Paginate large lists

More most-asked PHP 8 questions

← All PHP 8 questions