🔴 Laravel Intermediate

What are sub-queries in Laravel Eloquent?

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.