PHP
Efficient Eager Loading with Conditional Constraints
Optimize Laravel Eloquent queries by eager loading relationships with specific conditions, reducing N+1 issues and memory usage for relevant data.
use App\Models\User;
use App\Models\Post;
// Load users and only their published posts
$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 . " (Published)
";
}
}
// Example with nested relationships and constraints
// Assuming a Post has many Comments, and a Comment belongs to a User
$posts = Post::with(['user', 'comments' => function ($query) {
$query->where('approved', true)->with('user'); // Eager load comment's user
}])->get();
foreach ($posts as $post) {
echo "Post: " . $post->title . "
";
echo "Author: " . $post->user->name . "
";
foreach ($post->comments as $comment) {
echo " - Comment by " . $comment->user->name . ": " . $comment->body . "
";
}
}
How it works: This snippet demonstrates how to eager load relationships in Laravel Eloquent with specific conditions. Instead of loading all related posts for every user, the `with()` method accepts a closure that allows you to add `where` clauses or other query constraints to the relationship query itself. This is crucial for optimizing database performance by fetching only the necessary related data, effectively tackling the N+1 query problem while also filtering results. The second example shows how to apply this to nested relationships.