I need to list all the conversations of a user, sorting by the last received message (same as the conversations of whatsApp).
In this way it orders correctly, but duplicates the conversations.
I tried to use distinct() to solve this, but it ended up asking to put the messages.created_at inside the select, then it duplicates the results again.
Chat::where('chats.from_id', $user_id)
->join('messages', 'chats.id', '=', 'messages.chat_id')
->select('chats.*')
->orderBy('messages.created_at', 'desc')
->get();
Use this:
Chat::where('chats.from_id', $user_id)
->join('messages', 'chats.id', '=', 'messages.chat_id')
->select('chats.*', DB::raw('max(messages.created_at) latest_message'))
->groupBy('chats.id')
->orderBy('latest_message', 'desc')
->get();
You can also use relationships, e.g.:
Chat::where('chats.from_id', $user_id)
->withCount(['messages as latest_message' => function($query) {
$query->select(DB::raw('max(created_at)'));
}])
->orderByDesc('latest_message')
->get();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With