PHP
Eager Loading Relationships with Conditions in Laravel Eloquent
Learn to efficiently load only specific related models in Laravel Eloquent using eager loading with constraints, optimizing database queries and data retrieval.
use App\Models\User;
use App\Models\Post;
// Load users and only their published posts
$usersWithPublishedPosts = User::with(['posts' => function ($query) {
$query->where('is_published', true);
}])->get();
foreach ($usersWithPublishedPosts as $user) {
echo "User: " . $user->name . "
";
foreach ($user->posts as $post) {
echo " - Published Post: " . $post->title . "
";
}
}
// Example 2: Load posts and the user who has at least one published post (whereHas)
$postsWithPublishedUser = Post::whereHas('user', function ($query) {
$query->where('is_active', true); // Assuming 'is_active' is on the user model
})->with('user')->get();
foreach ($postsWithPublishedUser as $post) {
echo "Post: " . $post->title . "
";
echo " - User: " . $post->user->name . " (Active: " . ($post->user->is_active ? 'Yes' : 'No') . ")
";
}
How it works: This snippet demonstrates how to eager load related models while applying specific conditions to the relationship query. The `with()` method accepts a closure, allowing you to add `where` clauses or other query builders to the related model's query. This prevents loading unnecessary related data, significantly improving performance. The `whereHas()` method is used to filter parent models based on conditions applied to their relationships.