MR
Eloquent performance: Lazy loading vs Eager loading benchmark
I ran some benchmarks on lazy loading vs eager loading in a project with around 50K records and wanted to share results.
Setup: Blog posts with authors, categories, and tags (polymorphic).
Lazy loading (N+1 problem):
Post::all() then accessing post->author in a loop.
Result: 523 queries, 2.8 seconds.
Eager loading:
Post::with(['author', 'category', 'tags'])->get()
Result: 4 queries, 0.12 seconds.
That is a 23x improvement. Always use with() to eager load your relations. Also, calling preventLazyLoading() in AppServiceProvider is a lifesaver during development because it throws exceptions when you accidentally lazy load.
Anyone have other Eloquent performance tips to share?