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.