following code will return users with their latest published post
$latestPosts = DB::table('posts')
                   ->select('user_id', DB::raw('MAX(created_at) as last_post_created_at'))
                   ->where('is_published', true)
                   ->groupBy('user_id');

$users = DB::table('users')
        ->joinSub($latestPosts, 'latest_posts', function ($join) {
            $join->on('users.id', '=', 'latest_posts.user_id');
        })->get();
by გიორგი უზნაძე
4 years ago
Laravel
Eloquent
1
Pro tip: use ```triple backticks around text``` to write in code fences