I am developing basic messaging functionality in Laravel and want to display every user who sent a message to the currently logged in user and the last message received, the problem is that "orderByDesc" is not working properly it displays the first message instead of the last One piece.
This is the query I wrote:
$receivedmessages = DB::table('messages') ->join('users', 'users.id', '=', 'messages.sender_id') ->select('messages.*', 'users.username') ->where('receiver_id', Auth::user()->id) ->orderByDesc('messages.created_at') ->groupBy('receiver_id') ->get();
Any idea how to solve this problem? Thanks
Remove
->where('receiver_id', Auth::user()->id)
This condition to get results for each user instead of the one you logged in withThe trick to achieve the above is to get the max Id's from the table and use those Id
conditionin a
WHERE IN