0
0
Laravelframework~5 mins

Lazy loading and N+1 prevention in Laravel

Choose your learning style9 modes available
Introduction

Lazy loading helps load related data only when needed. N+1 problem happens when many database queries run unnecessarily. Preventing it makes apps faster and smoother.

When showing a list of users with their posts on a page
When loading products with their categories in an online store
When displaying comments with their authors on a blog
When fetching orders with their customer details
Syntax
Laravel
Model::with('relation')->get();

with() loads related data eagerly to avoid extra queries.

Lazy loading happens automatically when you access a relation property.

Examples
Loads all users and their posts in two queries, preventing N+1 problem.
Laravel
$users = User::with('posts')->get();
This causes N+1 problem because each post loads its user separately.
Laravel
$posts = Post::all();
foreach ($posts as $post) {
  echo $post->user->name;
}
Prevents N+1 by loading all users with posts in one go.
Laravel
$posts = Post::with('user')->get();
foreach ($posts as $post) {
  echo $post->user->name;
}
Sample Program

This code loads all users and their posts in just two queries. It then prints each user and their posts. This avoids the N+1 problem where each user's posts would be loaded separately.

Laravel
<?php
use App\Models\User;

// Fetch users with posts eagerly to prevent N+1
$users = User::with('posts')->get();

foreach ($users as $user) {
    echo "User: {$user->name}\n";
    foreach ($user->posts as $post) {
        echo "- Post: {$post->title}\n";
    }
}
OutputSuccess
Important Notes

Use with() to load relations eagerly and avoid many small queries.

Lazy loading is simple but can cause performance issues if not careful.

Check queries in Laravel Debugbar or log to spot N+1 problems.

Summary

Lazy loading loads related data only when accessed.

N+1 problem happens when many queries run for related data.

Use with() to load relations eagerly and prevent N+1.