← Back to all snippets
PHP

Efficient Eager Loading of Eloquent Relationships with Constraints

Optimize database queries by eager loading Eloquent relationships with specific conditions, preventing N+1 problems and improving application performance.

Post::with(['comments' => function ($query) {
    $query->where('approved', 1);
}])->get();
How it works: This snippet demonstrates eager loading the `comments` relationship for `Post` models, but critically, it applies a constraint (`where('approved', 1)`) directly to the `comments` query. This ensures that only approved comments are loaded, even when eager loading, preventing the N+1 query problem while efficiently filtering related data.

Need help integrating this into your project?

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

Hire DigitalCodeLabs