Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

KikoLdasd's avatar

How do I make a query to take conversations between two people chat system

Hi, I tried to make a chat system in laravel + vue one to one and I got a little stuck on the side when I have to take the conversations between two people I structured the database like this

 $table->bigIncrements('id');
            $table->bigInteger('receiver')->unsignedBigInteger();
            $table->bigInteger('sender')->unsignedBigInteger();
            $table->text('message');
            $table->timestamps();

I have messages between the user and the receiver in the database

"messages": [
        {
            "id": 9,
            "receiver": 1,
            "sender": 2,
            "message": "How you are?",
            "created_at": "2022-05-25T17:20:33.000000Z",
            "updated_at": "2022-05-25T17:20:33.000000Z"
        },

		{
            "id": 9,
            "receiver": 2,
            "sender": 1,
            "message": "I am good, you?",
            "created_at": "2022-05-25T17:20:33.000000Z",
            "updated_at": "2022-05-25T17:20:33.000000Z"
        },

      {
            "id": 9,
            "receiver": 1,
            "sender": 2,
            "message": "I am good. Thank you",
            "created_at": "2022-05-25T17:20:33.000000Z",
            "updated_at": "2022-05-25T17:20:33.000000Z"
        },
    ]

How can I make a query so that I can take the conversations between the two? I tried like this

return Message::query()
            ->where(['sender' => $senderId, 'receiver' => $receiverId])
            //->orWhere(['sender' => $senderId, 'receiver' => $receiverId])
            ->get();
{
    "messages": [
        {
            "id": 9,
            "receiver": 1,
            "sender": 2,
            "message": "Hey, I am good. You?",
            "created_at": "2022-05-25T17:20:33.000000Z",
            "updated_at": "2022-05-25T17:20:33.000000Z"
        }
    ]
}

But I don't really understand how I could proceed in this case, it will only come to me for id 1 with id 2 but not id 2 with id 1 Do you have any examples I can take?

0 likes
3 replies
coder2's avatar

Try this please:

$myId = 1;
$otherPerson = 2;

return Message::query()
    ->where(function ($query) use ($myId, $otherPerson) {
        return $query->where('sender', $myId)
            ->where('receiver', $otherPerson);
    })->orWhere(function ($query) use ($myId, $otherPerson) {
        return $query->where('sender', $otherPerson)
            ->where('receiver', $myId);
    })->get();
1 like
iAmBsquare's avatar

SELECT * FROM messages WHERE (sender = 1 AND receiver = 2) OR (receiver = 1 AND sender = 2);

1 like

Please or to participate in this conversation.