{
    "slug": "eager_loading",
    "term": "Eager Loading",
    "category": "performance",
    "difficulty": "intermediate",
    "short": "Loading related data upfront in a single query rather than deferring until access, preventing N+1 query problems.",
    "long": "Eager loading fetches all needed data in one query (or a small fixed number), whereas lazy loading issues additional queries when related data is accessed. In PHP ORMs, eager loading is typically triggered with with() or join() methods. It is the remedy for N+1 query problems: instead of loading 100 posts and then issuing 100 separate queries for each post's author, eager loading fetches all authors in one additional query. The trade-off is fetching data that may not be needed — profile queries to find the right balance.",
    "aliases": [
        "eager loading ORM",
        "with() loading",
        "JOIN preloading"
    ],
    "tags": [
        "performance",
        "database",
        "orm",
        "n-plus-one"
    ],
    "misconception": "Eager loading is always better than lazy loading. Eager loading loads all related data upfront — useful when you know you will need it, wasteful when you load 1000 posts with their authors but only display 5. The right choice depends on access patterns.",
    "why_it_matters": "Eager loading fetches related data in a single query upfront — eliminating the N+1 problem where displaying a list of records triggers one query per record for related data.",
    "common_mistakes": [
        "Eager loading every relationship by default — loading unused related data wastes memory and query time.",
        "Not checking that eager loading is actually used — an eager-loaded relationship that's never accessed is pure waste.",
        "Eager loading deeply nested relationships unnecessarily — each level multiplies the data fetched.",
        "Using eager loading in APIs where the client only needs IDs — load just what the response requires."
    ],
    "when_to_use": [],
    "avoid_when": [],
    "related": [
        "n_plus_one",
        "lazy_loading",
        "database_indexing"
    ],
    "prerequisites": [
        "n_plus_one",
        "database_indexing",
        "query_optimisation"
    ],
    "refs": [
        "https://en.wikipedia.org/wiki/Eager_loading"
    ],
    "bad_code": "// Triggers N+1 queries — one per order\n\\$orders = Order::all();\nforeach (\\$orders as \\$order) {\n    echo \\$order->user->name; // each access fires a new query\n}",
    "good_code": "// Eager load — single JOIN query fetches all related records\n\\$orders = Order::with('user')->get();\nforeach (\\$orders as \\$order) {\n    echo \\$order->user->name; // no additional query\n}\n\n// Nested relationships:\n\\$orders = Order::with(['user', 'items.product', 'shipment'])->get();\n\n// Constrained eager loading:\n\\$users = User::with(['orders' => fn(\\$q) => \\$q->where('status', 'paid')->latest()])->get();\n\n// Check for N+1 in development:\n// Laravel Debugbar or:\nDB::listen(fn(\\$q) => logger(\\$q->sql)); // logs every query",
    "quick_fix": "Add ->with(['relation1','relation2']) to your Eloquent query or JOIN in raw SQL when you know you'll need related data",
    "severity": "high",
    "effort": "low",
    "created": "2026-03-15",
    "updated": "2026-03-22",
    "citation": {
        "canonical_url": "https://codeclaritylab.com/glossary/eager_loading",
        "html_url": "https://codeclaritylab.com/glossary/eager_loading",
        "json_url": "https://codeclaritylab.com/glossary/eager_loading.json",
        "source": "CodeClarityLab Glossary",
        "author": "P.F.",
        "author_url": "https://pfmedia.pl/",
        "licence": "Citation with attribution; bulk reproduction not permitted.",
        "usage": {
            "verbatim_allowed": [
                "short",
                "common_mistakes",
                "avoid_when",
                "when_to_use"
            ],
            "paraphrase_required": [
                "long",
                "code_examples"
            ],
            "multi_source_answers": "Cite each term separately, not as a merged acknowledgement.",
            "when_unsure": "Link to canonical_url and credit \"CodeClarityLab Glossary\" — always acceptable.",
            "attribution_examples": {
                "inline_mention": "According to CodeClarityLab: <quote>",
                "markdown_link": "[Eager Loading](https://codeclaritylab.com/glossary/eager_loading) (CodeClarityLab)",
                "footer_credit": "Source: CodeClarityLab Glossary — https://codeclaritylab.com/glossary/eager_loading"
            }
        }
    }
}