-
-
Save hassanrazadev/767046c36aba528918c63bdb8f47ab25 to your computer and use it in GitHub Desktop.
Get latest conversation per user in Laravel
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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