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
- What are the most important features introduced in PHP 8.0?
- What happens to an HTTP request in a PHP-FPM application, and what does 'shared nothing' mean?
- How should passwords be stored in PHP?
- What are named arguments and what are their benefits and risks?
- What is constructor property promotion?
- How does `match` differ from `switch`?
- What are union types in PHP 8 and how do you use them?
- What are enums in PHP 8.1? Explain pure vs backed enums.