PHP
Optimize Eloquent Queries with Eager Loading
Prevent N+1 query problems in Laravel Eloquent by efficiently loading relationships using eager loading (`with()` method), significantly boosting application performance.
use App\Models\Post;
// Without eager loading (potential N+1 problem)
$posts = Post::all();
foreach ($posts as $post) {
echo $post->user->name; // Each access triggers a new query if not loaded
}
// With eager loading (solves N+1)
$posts = Post::with('user', 'comments')->get();
foreach ($posts as $post) {
echo $post->user->name; // User and comments are already loaded
foreach ($post->comments as $comment) {
echo $comment->body;
}
}
// Eager loading specific columns or nested relationships
$posts = Post::with(['user:id,name', 'comments' => function ($query) {
$query->where('approved', true);
}])->get();
How it works: Eager loading with the `with()` method allows you to load all of a model's relationships when querying the parent model. Instead of making a separate database query for each relationship accessed (the 'N+1 problem'), eager loading performs only a few additional queries to fetch all related models at once, drastically improving application performance and reducing database load.