← Back to all snippets
PHP

Efficiently Eager Load Relationships with Conditions

Optimize database queries by eagerly loading related Eloquent models only when specific conditions are met on the relationship itself, improving performance.

class Post extends Model
{
    public function comments()
    {
        return $this->hasMany(Comment::class);
    }
}

class Comment extends Model
{
    // ...
}

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

foreach ($posts as $post) {
    echo "Post: " . $post->title . "
";
    foreach ($post->comments as $comment) {
        echo "  - Approved Comment: " . $comment->body . "
";
    }
}
How it works: This snippet demonstrates how to eagerly load relationships in Laravel Eloquent while applying specific constraints to the loaded relationship. Instead of loading all comments, we use a closure within the `with()` method to filter only `approved` comments for each post. This optimizes database queries by fetching only necessary related data, preventing the N+1 problem while also filtering results efficiently.

Need help integrating this into your project?

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

Hire DigitalCodeLabs