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

Kris01's avatar

Chat System Database - Relationships

I'm building a chat system

I have three tables

Users 

Chats
      - member_one_id
      - member_two_id
   
Messages
      - sender_id
      - text

A User can HAVE MANY Chats, so I made the laravel relationship, but I have a problem, since I have two foreign keys linked to users in chats table.

How would the laravel eloquent relationship look for these tables?

I am unable to retrieve the chats a user has.

0 likes
1 reply
LaryAI's avatar
Level 58

To set up the relationships between these tables, you can use Laravel's hasMany and belongsTo methods. Here's an example of how you can set up the relationships:

In your User model:

public function chats()
{
    return $this->hasMany(Chat::class, 'member_one_id')->orWhere('member_two_id', $this->id);
}

In your Chat model:

public function userOne()
{
    return $this->belongsTo(User::class, 'member_one_id');
}

public function userTwo()
{
    return $this->belongsTo(User::class, 'member_two_id');
}

public function messages()
{
    return $this->hasMany(Message::class);
}

In your Message model:

public function chat()
{
    return $this->belongsTo(Chat::class);
}

public function sender()
{
    return $this->belongsTo(User::class, 'sender_id');
}

With these relationships set up, you can retrieve the chats a user has like this:

$user = User::find($userId);
$chats = $user->chats;

This will return a collection of Chat models that the user is a member of. You can then access the messages for each chat like this:

foreach ($chats as $chat) {
    $messages = $chat->messages;
}

Please or to participate in this conversation.