What is Laravel Eloquent Eager Loading
What is Eager Loading ?
At a basic level, ORMs are model data on “lazy” load. After all, how can the ORM know your intent? Maybe you will never really use the data of the relevant model after you query the model. Not optimizing the query is known as the “N+1” problem. When you use objects to represent queries, you may be making queries without even realizing it.
In this tutorial, we will set up some example relationships and then walk through how queries change with and without eager loading. I like to get my hands directly on code and experiment with things, and I hope to illustrate how eager loading works with some examples that will further help you understand how to optimize your queries.
From this point on in the article, I’ll be speaking in more Laravel-esque terms but still keep the idea as general as possible, so here we go!
I got two DB tables:
Posts
$table->increments('id');
$table->integer('comment_id')->unsigned();
$table->foreign('comment_id')->references('id')->on('comments');
2. Comments
$table->increments('id');
$table->string('message', 70);
Let’s see what we did wrong
We are not telling the model that we need all the authors, so an individual query happens each time we get the comment messages from the individual Post
model instances.
$posts = Post::published()->get(); // one query$authors = array_map(function($post) { // Produces a query on the author model
return $post->comment->message;}, $posts);
If we try with lazy load
posts = Post.includes(:comment).limit(100)$posts = Post::with(‘comment’)->limit(100)->get();
Experimenting with Eager Loading
In the post model
public function comments(){
return $this->hasMany(Comment::class);
}
if we want to use it in controller
$posts = Post::with('comments')->latest()->get();
OR
$posts->map(function ($post) { return $post->comment; });