PHP

Efficient Conditional Eager Loading in Eloquent

Optimize Laravel Eloquent queries by conditionally eager loading related models using a closure, preventing N+1 problems while fetching specific data efficiently.

use App\Models\User;
use App\Models\Post;

// Get users and only their published posts
$users = User::with(['posts' => function ($query) {
    $query->where('is_published', true);
}])->get();

foreach ($users as $user) {
    echo "User: " . $user->name . "
";
    foreach ($user->posts as $post) {
        echo " - Published Post: " . $post->title . "
";
    }
}

// Example 2: Eager load comments only if the post has more than 5 comments
$posts = Post::with(['comments' => function ($query) {
    $query->has('user'); // Example constraint on the comment's user
}])
->has('comments', '>', 5) // Constraint on the parent model (Post)
->get();

foreach ($posts as $post) {
    echo "Post: " . $post->title . "
";
    if ($post->relationLoaded('comments')) {
        echo " - Comments loaded (" . $post->comments->count() . "):
";
        foreach ($post->comments as $comment) {
            echo "   - " . $comment->content . "
";
        }
    } else {
        echo " - Comments not loaded (less than 5 comments).
";
    }
}
How it works: This snippet demonstrates how to eager load related models with specific conditions. By passing a closure to the `with()` method, you can add `where` clauses or any other query constraints to the eager-loaded relationship query. This is crucial for optimizing performance by avoiding the N+1 query problem while also filtering the related data to only what is needed, improving data retrieval efficiency.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs