#1 India's Top IT Training Institute
×

About Uncodemy

Know more about who we are and what we stand for.

About Us

About Us

Discover our mission to equip individuals with essential IT skills and industry expertise.

Read More →
UnCodeMy Gallery

UnCodeMy Gallery

Explore highlights from our IT training sessions and success stories.

Read More →
Mentors

Mentors

Meet the industry experts who train and guide you through your course.

Read More →
Free Resources

Free Resources

Free tutorials, interview questions, tools and calculators to help you learn.

Explore →
×

Free Resources

Learn, practice and plan your career — bilkul free.

Tutorials

Tutorials

Step-by-step written tutorials to learn any technology at your own pace.

Read More →
Free Counselling

Free Counselling

Book a free video counselling session and pick the right course for you.

Read More →
Online Compiler

Online Compiler

Write, run and test your code online — no setup required.

Read More →

Eager Loading and Lazy Loading

How and when Eloquent actually fetches related data has a big impact on application performance. Laravel supports two approaches — lazy loading and eager loading — and choosing the right one avoids one of the most common Eloquent performance pitfalls.

Lazy Loading

By default, relationships are loaded lazily: the related data is only fetched from the database the moment it's actually accessed. This is convenient, but it becomes a problem inside a loop, where accessing a relationship on each item triggers a brand-new query every time — known as the N+1 query problem.

Eager Loading

Eager loading solves this by fetching a model's relationships upfront, in a small, fixed number of queries, using the with() method. Instead of one query per record, related data for an entire collection is retrieved in just one or two additional queries.

ApproachQuery BehaviorBest For
Lazy loadingOne query per relationship accessAccessing a relationship occasionally, outside a loop
Eager loading (with())A small, fixed number of queries upfrontLooping through a collection and using its relationships

Spotting and Preventing N+1 Issues

Eager loading works well for one-to-many and many-to-many relationships alike, but many-to-many connections have an extra piece worth understanding on their own: the pivot table.

Seeing the N+1 Problem in Real Code

Take a blog listing that shows each post with its author's name. The lazy version looks innocent:

$posts = Post::all();                 // 1 query

foreach ($posts as $post) {
    echo $post->author->name;         // 1 extra query per post
}

With 50 posts this runs 51 queries. The eager version asks for the authors up front:

$posts = Post::with('author')->get();  // 2 queries in total

foreach ($posts as $post) {
    echo $post->author->name;          // no new query
}

Behind the scenes Eloquent runs one query for the posts, collects every author_id, runs a single WHERE id IN (...) query for the authors, and matches them in memory. The number of queries stays the same whether you show ten posts or a thousand.

Useful Eager Loading Variations

NeedCode
Several relationshipsPost::with(['author', 'tags'])->get()
Nested relationshipsPost::with('comments.user')->get()
Only certain columnsPost::with('author:id,name')->get()
Filtered related rowsPost::with(['comments' => fn ($q) => $q->where('approved', true)])->get()
Just a countPost::withCount('comments')->get(), then use $post->comments_count
Load after fetching$posts->load('author')

When selecting columns, always include the primary key and any foreign key, otherwise Eloquent cannot match related records and the relationship comes back empty. The load() method, sometimes called lazy eager loading, is handy when you decide to load a relationship only after checking a condition.

Catching N+1 Queries Early

Laravel can refuse lazy loading during development so mistakes show up as errors instead of slow pages. Add this to the boot() method of AppServiceProvider:

use Illuminate\Database\Eloquent\Model;

public function boot(): void
{
    Model::preventLazyLoading(! app()->isProduction());
}

Now any accidental lazy load throws an exception locally, while production users are never affected. Tools such as Laravel Debugbar or Laravel Telescope show the number of queries per request, which is the quickest way to spot a loop that suddenly fires hundreds of them.

When Lazy Loading Is Still Fine

  • Loading a relationship for a single model, for example one post on its detail page.
  • A relationship used only in a rare branch, where eager loading would waste a query most of the time.

Also avoid the opposite mistake: adding many relationships to a model's $with property so they load on every query. That hides cost and fetches data many pages never use. Eager load explicitly where the data is needed.

A simple review habit helps: whenever a Blade view or API resource loops over a collection, check which relationships are used inside the loop and make sure the controller loads them with with(). Doing this in code review catches most performance problems before they ever reach users.

Ready to master Laravel Training Course?

Join Uncodemy's hands-on Laravel program and build real, production-ready applications.

Explore Course