PHP

Eager Load Relationships with Specific Conditions

Optimize Laravel Eloquent queries by eager loading relationships only if they meet certain conditions, preventing N+1 issues and filtering related data efficiently.

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

// Fetch posts and only load active comments
$posts = Post::with(['comments' => function ($query) {
    $query->where('is_active', true);
}])->get();

foreach ($posts as $post) {
    echo $post->title;
    foreach ($post->comments as $comment) {
        echo "- " . $comment->body;
    }
}
How it works: This snippet demonstrates how to eager load a relationship (`comments`) while applying specific conditions (`where('is_active', true)`) to the *related* model's query. This prevents the N+1 query problem and ensures that only relevant related data is loaded, optimizing performance and data retrieval by fetching all necessary related records in a single additional query, instead of one query per parent record.

Need help integrating this into your project?

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

Hire DigitalCodeLabs