$ lexprog.com

// notes from an old coder -- php, databases, and the occasional rant

[March 12, 2025] Eloquent ORM

Eloquent Lazy vs Eager Loading

Eloquent Lazy vs Eager Loading

────────────────────────────────────────────────────────

Eloquent Lazy vs Eager Loading

Tip: Eager Load with with()

$posts = Post::with('author', 'comments')->get();

3 queries total instead of N+1.

Gotcha: Over-Eager Loading

Post::with('author', 'comments', 'tags', 'category')->get();

Loading unnecessary relations wastes memory and time.

Tip: Lazy Load with load()

$posts = Post::all();
$posts->load('author');

Use when you're not sure you need the relation.

Gotcha: with() on Specific Relations

Post::with(['comments' => fn($q) => $q->where('approved', true)])->get();

Tip: loadCount() for Counts

$post->loadCount('comments');
echo $post->comments_count;

Gotcha: Nested Eager Loading

Post::with('author.posts')->get();

Loads author and their posts. Be careful with deep nesting.

Tip: Use cursor() for Memory-Neutral Iteration

When exporting 100K rows, get() loads everything into memory. cursor() uses yield and keeps memory flat regardless of row count. Perfect for artisan commands.

Tip: whereHas() vs load() — Two Different Things

whereHas() filters the parent query by relationship existence. load() eager-loads relationships AFTER the query. Mixing them up is a common source of logic bugs.

Gotcha: withCount() Adds a Subquery

withCount('comments') runs a correlated subquery on every row. On large tables, this can be slower than a separate query. Profile before relying on it.

Senior Insight

Lazy loading is convenient during development, but it's a performance disaster in production if not caught. Since Laravel 8, Model::preventLazyLoading() has been available, and I enable it in all environments except production. For production, I use Model::handleLazyLoadingViolationUsing() to log lazy loading attempts instead of throwing exceptions, creating a performance regression detection system.

Source: Laravel Docs (https://laravel.com/docs/eloquent), Laravel News (https://laravel-news.com/), Freek.dev (https://freek.dev/tags/eloquent)

────────────────────────────────────────────────────────
<-- back to posts