PHP

Optimizing Relationship Loading with Lazy Eager Loading

Improve performance by using Laravel Eloquent's lazy eager loading to efficiently load relationships for a collection of models that have already been retrieved, avoiding N+1 queries.

use App\Models\User;

// Retrieve a collection of users without their posts
$users = User::where('active', true)->take(10)->get();

// At a later point, you realize you need the posts for these users.
// Instead of looping and calling $user->posts (N+1), use lazy eager loading.
$users->load('posts');

// Now, accessing $user->posts for any user in the collection
// will not trigger an N+1 query.
foreach ($users as $user) {
    echo "User: ".$user->name." has ".$user->posts->count()." posts.
";
}

// You can also apply constraints to the relationship being lazy loaded:
$users->load(['posts' => function ($query) {
    $query->where('status', 'published')->orderByDesc('created_at');
}]);
How it works: Lazy eager loading allows you to eager load relationships on an Eloquent collection that has already been retrieved from the database. This is particularly useful when you initially fetch models without their relationships, but later in the request cycle, you discover you need access to a related model. Using the `load()` method on a collection prevents the N+1 query problem by fetching all related models in a single query, significantly improving performance.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs