How do I use eager loading to improve query performance in Eloquent?
Jun 20, 2025 am 12:14 AMEager loading in Eloquent reduces queries by preloading relationships upfront. Lazy loading causes the N 1 query problem, where looping through 100 users and accessing their profiles results in 101 queries. To fix this, use with() to eager load relationships like User::with('profile')->get(), which executes just two queries. You can load multiple relationships with User::with(['profile', 'posts'])->get(), or nested ones like User::with('posts.comments')->get(). Add constraints using closures such as filtering only published posts or sorting them by date. Avoid over-eager loading unnecessary data, as it wastes memory and performance. Only load what’s needed for the current request.
Eager loading in Eloquent is one of the most effective ways to reduce the number of queries executed when retrieving related models, especially when working with large datasets. The main idea is to load all needed relationships upfront instead of querying them on demand later.
Why Lazy Loading Can Be Costly
By default, Eloquent uses lazy loading for relationships. That means if you loop through a collection and access a relationship inside the loop, Eloquent will run a new query each time.
For example:
$users = User::all(); foreach ($users as $user) { echo $user->profile->bio; }
If there are 100 users, this will result in 101 queries — one to get all users, and 100 more to fetch each user’s profile. This is commonly referred to as the "N 1 query problem."
That's where eager loading comes in handy.
How to Use with()
for Eager Loading
The simplest and most common way to eager load relationships is by using the with()
method when querying your model.
Example:
$users = User::with('profile')->get();
In this case, Eloquent will execute two queries: one for all users and another to get all related profiles. It then matches them efficiently in PHP, which is much faster than doing it per model.
You can also eager load multiple relationships at once:
$users = User::with(['profile', 'posts'])->get();
And even nested relationships:
$users = User::with('posts.comments')->get();
This tells Eloquent to also load comments for each post made by the user.
Tip: If you're not sure whether a relationship exists, use
with()
anyway. It still performs better than not using it when the data is present.
Conditional Eager Loading with Constraints
Sometimes you may want to eager load a relationship but only include certain results — like only active posts or recent comments.
You can add constraints to your eager loading by passing a closure:
$users = User::with(['posts' => function ($query) { $query->where('published', true); }])->get();
This loads only published posts for each user.
Or sort the results:
$users = User::with(['posts' => function ($query) { $query->orderBy('created_at', 'desc'); }])->get();
You can even combine conditions and sorting:
- Filter posts that are published
- Sort them by date
- Limit to 5 most recent ones
However, note that limiting in eager loading isn’t directly supported in base Eloquent (you'd need a package or custom logic), so keep that in mind for advanced filtering.
Avoid Over-Eager Loading
While eager loading improves performance, don't fall into the trap of loading everything just in case.
Only eager load what you actually need for the current request or view. Loading unnecessary data increases memory usage and could slow things down too.
For example, if you're displaying a list of users without any profile or post data, there’s no reason to call:
User::with(['profile', 'posts', 'roles', 'comments'])->get();
It might seem safe, but it's wasteful.
Stick to what your page needs right now.
That's basically how eager loading works in Eloquent. It's not complicated, but it makes a huge difference when used correctly.
The above is the detailed content of How do I use eager loading to improve query performance in Eloquent?. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

This article brings you relevant knowledge about Laravel. It mainly introduces to you the implementation of optimistic locking in the Laravel Eloquent model. There are code examples. Friends who are interested can take a look below. I hope it will be helpful to you.

Laravel development: How to use LaravelEloquent to implement polymorphic associations? Polymorphic association is an important feature of Laravel Eloquent, which allows one model to establish relationships with multiple different models. In practical applications, processing different types of data is relatively simple and efficient, especially in database design. In this article, we will discuss how to implement polymorphic associations using Laravel Eloquent. 1. What is a polymorphic association? Polymorphism

Converting an array into an object using Eloquent in Laravel requires the following steps: Create an Eloquent model. Use Eloquent's select method to get the result and convert it to an array. Use ArrayObject to convert an array into an object. Gets an object property to access an array's values.

Laravel is a popular PHP framework that includes the powerful ORM (Object Relational Mapping) library-LaravelEloquent. This library is very powerful and can help us easily implement model association, making it easier to manage and query data. But many developers don't know how to use Laravel Eloquent to implement model association. In this article, I will introduce how to implement model association using Laravel Eloquent. 1. Laravel

Laravel is a popular PHP web framework that is popular due to its simplicity and ease of use. The Laravel framework is known for its excellent implementation of EloquentORM, an Object-RelationalMini mapping that supports the use of PHP to define database models and provides easy database interaction based on these models. This article will detail how to build a model using Laravel Eloquent to interact with the database quickly and reliably.

Laravel development: How to build a database model using LaravelEloquent? Laravel is a popular PHP framework that provides a powerful and easy-to-use database operation tool - Laravel Eloquent. In the past, using PHP to perform database operations inevitably required writing a large number of lengthy SQL statements and cumbersome codes. However, using Laravel Eloquent can easily build database models and achieve rapid development and maintenance. This article

As developers' needs for data interaction continue to grow, ORM has become an indispensable part of modern development. It can hide database operations in the background and provide a simplified API for CRUD operations. Among these ORM libraries, Eloquent has attracted the attention of many developers because it has been widely used in the Laravel framework. In PHP 8.0, Eloquent comes as a standalone extension library and can now be used in your projects. In this article we will explore Eloq

ThinkPHP6 is a very popular PHP framework, and Laravel is another popular PHP framework. Both frameworks have their own features and advantages, but Laravel's EloquentORM (Object Relational Mapping) engine is known as "the best ORM in the PHP world". What should we do if we want to use Laravel's EloquentORM when using ThinkPHP6? Let us discuss ThinkPHP in detail below
