Challenge 3: Fix an N+1 Across Two Relationship Types — Possible Solution ==================================================================== // BEFORE — N+1 for BOTH relationships use App\Models\Book; $books = Book::all(); // 1 query foreach ($books as $book) { echo $book->title . "\n"; echo $book->author->name . "\n"; // +1 query PER book (belongsTo) foreach ($book->tags as $tag) { // +1 query PER book (belongsToMany) echo $tag->name . "\n"; } } // Total for N books: 1 + N + N = 1 + 2N queries // AFTER — fixed with a single with() call $books = Book::with(['author', 'tags'])->get(); foreach ($books as $book) { echo $book->title . "\n"; echo $book->author->name . "\n"; // already loaded — no extra query foreach ($book->tags as $tag) { // already loaded — no extra query echo $tag->name . "\n"; } } // Total, regardless of N: exactly 3 queries (books, authors, tags) WHY THIS WORKS -------------- - Book::with(['author', 'tags'])->get() passes an ARRAY of relationship names to a single with() call — this is the "one mechanism, any relationship type" simplification the chapter highlighted: author is a belongsTo relationship and tags is a belongsToMany relationship, but both are eager-loaded through the exact same with() method, unlike Django where a belongsTo-equivalent (ForeignKey) needs select_related() while a belongsToMany-equivalent (ManyToMany) needs the separate prefetch_related() method. - Under the hood, Eloquent still runs multiple queries — one for the books themselves, one that fetches all the relevant authors in a single batched query, and one that fetches all the relevant tags (via the pivot table) in another single batched query — but critically, each of those runs exactly ONCE regardless of how many books are in the collection, rather than once per book. - The total query count (3, in this case) is the concrete signal that the N+1 problem has actually been solved: it no longer scales with the number of books returned, exactly the same verification approach used when this problem was fixed in Rails and Django earlier in this project.