Intermediate LevelLaravel
What is the N+1 Query Problem and how does Eager Loading (with) fix it?
❓ Interview Prompt: Explain N+1 query performance bug, lazy loading vs eager loading (Model::with()), constrained eager loading, and Model::preventLazyLoading().
The N+1 Query Problem occurs when accessing a model relationship inside a loop executes 1 query for the parent models plus N separate queries for each child model!
Fix (Eager Loading):
Use 'Book::with("author")->get()'. Eloquent executes exactly 2 SQL queries ('SELECT FROM books' and 'SELECT FROM authors WHERE id IN (...)').
Strict Safety: Enable 'Model::preventLazyLoading(! app()->isProduction())' in development to throw exceptions on N+1 bugs!
Code Implementation Example
php
<?php
use AppModelsBook;
use IlluminateDatabaseEloquentModel;
// Enable strict N+1 detection in development (AppServiceProvider)
Model::preventLazyLoading(! app()->isProduction());
// Eager Loading relationship efficiently
$books = Book::with(['author', 'publisher'])->get();💡Enabling strict N+1 detection and eager loading relationships with with().
🎯 Interview Key Takeaway
Always eager load relationships using with() to eliminate N+1 queries, and enable Model::preventLazyLoading() in development.
#N+1 Problem#Eager Loading#Performance#Intermediate
Back to all Laravel Questions→