Search code examples
sqllaravellaravel-query-builder

How to get recent conversations Laravel


I can already do this using the follow SQL command

SELECT * FROM users AS u INNER JOIN messages AS m ON u.ID IN (m.senderID, m.recipientID) WHERE u.ID <> $userID GROUP BY u.ID ORDER BY m.created_at DESC

How do I convert it to Laravel query builder, I have a Message model and User model


Solution

  • Do like this :

    $users  = User::join('messages', 'users.ID', '=', 'messages.user_id')
                ->whereIn('users.ID',['messages.senderId', 'messages.recipientID'])
                ->where('users.ID', '!=', $userID)
                ->groupBy('users.ID')
                ->orderBy('created_at','DESC')
                ->get();