TL;DR: Need latest message from each sender.
In my Laravel application I have two tables:
Users:
Messages:
I found this solution in another forum, I think that is what you were looking for. I post it so it can be useful for other users
DB::select('
SELECT t1.*
FROM messages AS t1
INNER JOIN
(
SELECT
LEAST(sender_id, recipient_id) AS user_id,
GREATEST(sender_id, recipient_id) AS recipient_id,
MAX(id) AS max_id
FROM messages
GROUP BY
LEAST(sender_id, recipient_id),
GREATEST(sender_id, recipient_id)
) AS t2
ON LEAST(t1.sender_id, t1.recipient_id) = t2.sender_id AND
GREATEST(t1.sender_id, t1.recipient_id) = t2.recipient_id AND
t1.id = t2.max_id
WHERE t1.sender_id = ? OR t1.recipient_id = ?
', [auth()->guard('api')->user()->id, auth()->guard('api')->user()->id]);
original post: https://laracasts.com/discuss/channels/laravel/get-the-latest-message-of-chat-model-with-mysql-just-cannot-get-the-idea-how-to-do-this?page=1#reply=392529