PHP

Eager Loading Nested Relationships with Constraints

Learn how to optimize Laravel Eloquent queries by eagerly loading nested relationships with custom query constraints to prevent N+1 issues.

$users = User::with(['posts' => function ($query) {
    $query->where('is_published', true)->latest();
}, 'posts.comments'])->get();
How it works: This snippet demonstrates how to eager load nested relationships while applying constraints to the intermediate relation. By using a closure inside the 'with' method, we filter only published posts and order them by the latest, then further load their nested comments, efficiently solving the N+1 query problem.

Need help integrating this into your project?

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

Hire DigitalCodeLabs