0Pricing
PHP Academy · Lesson

Eager Loading and Query Scopes

Prevent N+1 queries with eager loading and reuse logic with query scopes.

The N+1 Problem

Lazy loading runs one query per model when accessing a relationship inside a loop — catastrophic at scale.

<?php
$posts = Post::all(); // 1 query
foreach ($posts as $post) {
    echo $post->author->name; // 1 query per post = N+1 total!
}

Eager Loading with with()

Solve N+1 by eager-loading relationships upfront in one extra query.

<?php
$posts = Post::with("author")->get(); // 2 queries total
foreach ($posts as $post) {
    echo $post->author->name; // no extra query
}

All lessons in this course

  1. Eloquent Models and Migrations
  2. CRUD with Eloquent
  3. Eloquent Relationships
  4. Eager Loading and Query Scopes
← Back to PHP Academy