In Laravel, “eager loading” refers to the process of loading related models when querying a parent model. This is in contrast to “lazy loading,” which loads the related models only when they are accessed.
Eager loading can improve the performance of your application by reducing the number of database queries that are needed to load a model and its relationships.
To use eager loading in Laravel, you can use the with
method on a query builder instance or an Eloquent model. For example, consider a User
model that has a one-to-many relationship with a Post
model:
$users = User::with('posts')->get();
This will retrieve all users and their associated posts in a single database query, using a “JOIN” clause to bring the data together. This is more efficient than loading the users and then issuing a separate database query for each user’s posts.
You can also use the eager
method to specify additional constraints on the eager-loaded relationships:
$users = User::with(['posts' => function ($query) {
$query->where('title', 'like', '%Laravel%');
}])->get();
This will retrieve all users and their associated posts that have a title containing the word “Laravel,” using a single database query.