Tutorials Courses Interview Prep (100 Q&A) AI Tools (50) Developer Tools (50) Tracks Pricing Plans Blog & Articles Contact Us
Laravel Advanced & Architecture 5-8 Years (Senior) Medium Production Scenario

How does Laravel’s Eloquent ORM prevent N+1 queries during polymorphic and nested eager loading with custom constraints?

Real-World Scenario / Incident Description

An endpoint fetching 50 posts with comments, comment authors, and polymorphic image attachments was executing 1,400 database queries, taking 4.2 seconds.

311 views • Updated 1 month ago

Constrained Nested & Morph Eager Loading

$posts = Post::query()
    ->with([
        'author:id,name,avatar',
        'comments' => function ($query) {
            $query->where('is_approved', true)
                  ->latest()
                  ->take(5)
                  ->with(['user:id,name']);
        },
        'imageable' => function (MorphTo $morphTo) {
            $morphTo->morphWith([
                Post::class => ['tags'],
                User::class => ['profile'],
            ]);
        }
    ])
    ->select(['id', 'user_id', 'title', 'slug', 'created_at'])
    ->paginate(20);

Prevention in Development:

Enforce strict loading in AppServiceProvider::boot():

Model::preventLazyLoading(! app()->isProduction());
Related Concepts: #Eloquent #N+1 Query #Eager Loading #Polymorphism #Optimization