0Pricing
PHP Academy · Lesson

Eager Loading and Query Scopes

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

Eager Loading and Query Scopes is a free PHP Academy lesson on CoddyKit — lesson 4 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the PHP Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

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
}

Eager Loading Multiple Relations

Load several relationships at once.

<?php
$posts = Post::with(["author", "tags", "comments"])->get();

Nested Eager Loading

Load nested relationships using dot notation.

<?php
$posts = Post::with("comments.author")->get();
// Loads posts, their comments, and each comment's author

Constrained Eager Loading

Apply conditions to the eager-loaded relationship.

<?php
$posts = Post::with(["comments" => function ($q) {
    $q->where("approved", true)->latest();
}])->get();

withCount()

Load the count of a related model without loading the related models themselves.

<?php
$posts = Post::withCount("comments")->get();
foreach ($posts as $post) {
    echo $post->comments_count;
}

Lazy Eager Loading (load())

Eager-load relationships on an already-retrieved collection with load().

<?php
$posts = Post::all();
// Later, when you know you need the authors:
$posts->load("author");

Global Query Scopes

Global scopes automatically add constraints to all queries for a model.

<?php
class PublishedScope implements \Illuminate\Database\Eloquent\Scope {
    public function apply(Builder $builder, Model $model): void {
        $builder->where("is_published", true);
    }
}

Local Query Scopes

Local scopes are reusable query constraints defined on the model as methods prefixed with scope.

<?php
class Post extends Model {
    public function scopePublished(Builder $query): void {
        $query->where("is_published", true);
    }
    public function scopeByUser(Builder $query, int $userId): void {
        $query->where("user_id", $userId);
    }
}
// Usage:
Post::published()->byUser(1)->latest()->get();

Combining Scopes

Chain multiple local scopes for readable, reusable query logic.

<?php
$posts = Post::published()
             ->byUser(auth()->id())
             ->orderBy("created_at", "desc")
             ->paginate(15);

Detecting N+1 in Development

Use Laravel Debugbar or run DB::enableQueryLog() to detect unexpected query counts during development.

Summary

Use with() to eager-load relationships and eliminate N+1 queries. Use withCount() for counts. Define local scopes for reusable, readable query constraints.

Quick Check

Which method eager-loads related models to solve N+1?

Frequently asked questions

Is the “Eager Loading and Query Scopes” lesson free?

Yes — the full text of “Eager Loading and Query Scopes” is free to read here on the web, and the PHP Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the PHP Academy course, upgrade to CoddyKit PRO.

What will I learn in “Eager Loading and Query Scopes”?

Prevent N+1 queries with eager loading and reuse logic with query scopes. You practise PHP Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start PHP Academy?

No prior experience is required. PHP Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 4 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “Eager Loading and Query Scopes” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this PHP Academy lesson?

Yes. Every PHP Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

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