PHP

Eager Load Eloquent Relationships with Custom Constraints

Optimize Laravel Eloquent queries by eagerly loading related models only if they meet specific conditions, preventing N+1 problems effectively.

use App\Models\Post;

$posts = Post::with(['comments' => function ($query) {
    $query->where('approved', true)->latest();
}])->get();

foreach ($posts as $post) {
    // $post->comments will only contain approved comments, ordered by latest
    foreach ($post->comments as $comment) {
        echo $comment->content . "
";
    }
}
How it works: This snippet demonstrates how to eagerly load the `comments` relationship for `Post` models, but only include comments that are `approved` and order them by the latest. This method efficiently resolves the N+1 query problem by fetching related data in a single query while allowing further customization of the eager-loaded relationship.

Need help integrating this into your project?

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

Hire DigitalCodeLabs