Eager Loading in Laravel allows you to preload related data for models to optimize database queries. This reduces the number of queries executed, preventing the N+1 query problem.
Eager Loading is part of Eloquent ORM and was introduced to optimize database interactions by fetching related data in advance.
Eager load a relationship:
$posts = Post::with('comments')->get();
Apply conditions to the relationship:
$posts = Post::with(['comments' => function ($query) {
$query->where('approved', true);
}])->get();
Eager Loading ensures efficient database queries, reducing response times and improving application performance.