🔴 Laravel Intermediate

What are Eloquent eager loading with constraints?

Why Interviewers Ask This

Mid-level Laravel roles require deep understanding of this topic. Interviewers ask this to separate candidates who truly understand the mechanics from those who only know surface-level concepts.

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.

Common Mistake

Don't just define the term — demonstrate that you understand when to use it and when not to. Showing awareness of trade-offs is what separates average from strong Laravel candidates.