PHP

Conditional Eager Loading for Relationships

Optimize Laravel database queries by eagerly loading specific relationships with additional constraints, efficiently fetching only relevant related data.

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

// Fetch all posts and their comments, but only load comments that are approved.
$postsWithApprovedComments = Post::with(['comments' => function ($query) {
    $query->where('approved', true);
}])->get();

foreach ($postsWithApprovedComments as $post) {
    echo "Post: " . $post->title . "
";
    foreach ($post->comments as $comment) {
        echo "- Approved Comment: " . $comment->body . "
";
    }
}

// Eager load users and only their active orders placed in the last month.
$recentActiveCustomers = User::with(['orders' => function ($query) {
    $query->where('status', 'active')
          ->where('created_at', '>=', now()->subMonth());
}])->where('is_active', true)->get();

foreach ($recentActiveCustomers as $user) {
    echo "User: " . $user->name . "
";
    foreach ($user->orders as $order) {
        echo "- Recent Active Order: " . $order->order_number . "
";
    }
}
How it works: Conditional eager loading allows you to not only eager load relationships (to prevent N+1 queries) but also apply specific constraints to the related models being loaded. By passing a closure to the `with()` method, you can modify the eager loading query, filtering the related results. This is extremely useful for optimizing performance by fetching only the necessary related data, reducing the dataset size and improving application efficiency.

Need help integrating this into your project?

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

Hire DigitalCodeLabs