All good. There is the following query:

$chat_list = ChatModel::where('creator', session()->get('id')) ->orWhere('reciever', session()->get('id')) ->get(); 

We get a list of all the messages in the chat, you need to group for individual chats with users. I already broke my head how to build a query, from my ideas - add an identifier to the chat. I ask for your help.

  • Do you want to group everything in one request and get a list of all strings or separate arrays for each chat? And bring the structure of the tables in the database, otherwise it will be a finger to the sky. - Vladimir Gonchar
  • @VladimirGonchar You are right. I want to group everything in one request. The table structure is as follows: id(int primary key), creator(int), reciever(int), text(text), created_at(datetime) . I thought about adding a chat identifier, then using the groupBy method - Vladislav

1 answer 1

Well, something like this might come up. It is only necessary to take into account that if ONLY_FULL_GROUP_BY is used in the database, then when adding fields to select, they will also need to be added to groupBy

  ChatModel::where('creator', session()->get('id')) ->orWhere('reciever', session()->get('id')) ->selectRaw('CASE creator > reciever THEN CONCAT(creator, "-", reciever) ELSE CONCAT(reciever, "-", creator) as user_pair') ->groupBy('user_pair') ->get();