PHP
Optimize Queries with Conditional Eager Loading in Laravel Eloquent
Learn how to efficiently load related models only when specific conditions are met, preventing N+1 queries and improving performance in Laravel applications.
use App\Models\User;
use App\Models\Post;
public function showUsersAndTheirPublishedPosts()
{
$users = User::with(['posts' => function ($query) {
$query->where('is_published', true)->latest();
}])->get();
foreach ($users as $user) {
echo "User: " . $user->name . "
";
foreach ($user->posts as $post) {
echo " - Post: " . $post->title . "
";
}
}
// Nested eager loading example: Load user's posts, and for each post, load its comments
$postsWithComments = Post::with('user', 'comments.user')->get();
foreach ($postsWithComments as $post) {
echo "Post: " . $post->title . " by " . $post->user->name . "
";
foreach ($post->comments as $comment) {
echo " - Comment: " . $comment->body . " by " . $comment->user->name . "
";
}
}
return view('users.index', compact('users', 'postsWithComments'));
}
How it works: This snippet demonstrates eager loading related models using Eloquent's `with()` method to prevent the N+1 query problem. It also shows how to add constraints to eagerly loaded relationships (e.g., only loading published posts) and how to perform nested eager loading (`comments.user`) for deeply related models, significantly improving query performance.