PHP

Eager Load Relationships with Conditional Constraints

Optimize Eloquent queries by eagerly loading only specific related models based on custom conditions, reducing N+1 issues and data overhead.

<?php

$users = App\Models\User::with(['posts' => function ($query) {
    $query->where('published_at', '<=', now());
}])->get();

foreach ($users as $user) {
    echo "User: " . $user->name . "
";
    foreach ($user->posts as $post) {
        echo " - Published Post: " . $post->title . "
";
    }
}
How it works: This snippet demonstrates how to eagerly load relationships while applying conditions to the related models. The `with()` method accepts an array where relationship names can be keys, and a closure as the value. This closure receives the relationship query builder, allowing you to add `where` clauses or any other query constraints to the related models being loaded, ensuring you only retrieve the specific related data needed.

Need help integrating this into your project?

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

Hire DigitalCodeLabs