Skip to content

Instantly share code, notes, and snippets.

@hassanrazadev
Created January 30, 2023 12:39
Show Gist options
  • Save hassanrazadev/767046c36aba528918c63bdb8f47ab25 to your computer and use it in GitHub Desktop.
Save hassanrazadev/767046c36aba528918c63bdb8f47ab25 to your computer and use it in GitHub Desktop.
Get latest conversation per user in Laravel
// Using Laravel/Eloquent
$userId = 1;
$messages = Message::select('*')
->where(function ($query) use ($userId) {
$query->where('to_id', $userId)
->orWhere('from_id', $userId);
})
->groupBy(DB::raw("CONCAT(LEAST(to_id, from_id), '.', GREATEST(to_id, from_id))"))
->selectRaw("MAX(id) as lastid")
->get();
$lastIds = $messages->pluck('lastid');
$conversations = Message::whereIn('id', $lastIds)
->orderBy('created_at', 'desc')
->get();
// using query builder:
$userId = 1;
$messages = DB::table('messages')
->where(function ($query) use ($userId) {
$query->where('to_id', $userId)
->orWhere('from_id', $userId);
})
->groupBy(DB::raw("CONCAT(LEAST(to_id, from_id), '.', GREATEST(to_id, from_id))"))
->selectRaw("MAX(id) as lastid")
->get();
$lastIds = $messages->pluck('lastid');
$conversations = DB::table('messages')
->whereIn('id', $lastIds)
->orderBy('created_at', 'desc')
->get();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment