Laravel Eloquent: Subqueries for Complex Queries
January 16, 2026
•
1 min read
•
24 views
Table of Contents
Power of subqueries:
Select Subquery
$users = User::addSelect(['latest_post' => Post::select('title')
->whereColumn('user_id', 'users.id')
->latest()
->take(1)
])->get();
Order by Subquery
$users = User::orderByDesc(
Post::select('created_at')
->whereColumn('user_id', 'users.id')
->latest()
->take(1)
)->get();
Where Subquery
$users = User::whereIn('id', function ($query) {
$query->select('user_id')
->from('posts')
->where('is_published', true);
})->get();
Related Posts
Laravel Sanctum API Authentication Complete Guide
Build secure API authentication with Laravel Sanctum for SPAs and mobile apps.
Laravel Rate Limiting: Protect Your Application
Implement rate limiting to protect your Laravel application from abuse.
Laravel Blade Components: Build Reusable UI
Create powerful reusable components with Laravel Blade.
Comments (0)
No comments yet. Be the first to comment!