🔴 Laravel Intermediate

What are Eloquent eager loading with constraints?

Answer

Constrained eager loading allows you to add additional query constraints to a relationship being eager-loaded. Instead of loading all comments, load only approved ones: Post::with(["comments" => fn($query) => $query->where("approved", true)->orderBy("created_at")])->get(). Multiple constrained relationships: Post::with(["comments" => fn($q) => $q->latest(), "tags" => fn($q) => $q->where("active", true)])->get(). Nested constrained loading: Post::with(["comments.author" => fn($q) => $q->select("id", "name")])->get(). Load counts with conditions: Post::withCount(["comments" => fn($q) => $q->where("approved", true)]). Without constraints, eager loading always loads the full relationship — constraints let you fetch only the data you need, reducing memory usage and query time for relationships with many records.