🔴 Laravel Intermediate

What are sub-queries in Laravel Eloquent?

Why Interviewers Ask This

Candidates at the intermediate level are expected to not only know this concept but explain the trade-offs involved. Interviewers use this question to see if you can reason about design decisions, not just recall facts.

Answer

Laravel supports sub-queries for adding computed columns from related tables without loading full relationships. Select sub-queries: User::addSelect(["last_login_at" => Login::select("created_at")->whereColumn("user_id", "users.id")->latest()->limit(1)])->get() — adds a last_login_at column to each user from the logins table in a single query. Order by sub-query: User::orderByDesc(Login::select("created_at")->whereColumn("user_id", "users.id")->latest()->limit(1)). Where sub-query: User::whereIn("id", Post::select("user_id")->where("published", true)). Sub-queries avoid N+1 problems for computed/aggregate data and express complex queries more cleanly than raw SQL. Use toSql() to inspect the generated query.

Pro Tip

This topic has Laravel-specific nuances that differ from general programming. Highlighting those nuances in your answer shows expertise rather than generic knowledge.