faa's avatar
Level 3

Chat database and relationship design

Hi all,

Am having a hard time to find out how to structure my tables and my relationships when creating a simple chat feature for my app.

I want it to be able to chat from both User to Clients and Clients to User ( I've added so they are both able to login to the system)

Here is my design so far. Can anyone see if am missing something?

Database design

Participant (pivot table)

  • sender_id
  • sender_type
  • conversation_id

Message

  • id
  • body
  • conversation_id
  • sender_id
  • sender_type

Conversation

  • id
  • subject
  • private

Model relationships

Participant

public function conversation()
{
    return $this->belongsTo(Conversation::class);
}

Message

public function sender()
{
    return $this->morphTo();
}

public function conversation()
{
    return $this->belongsTo(Conversation::class);
}

Conversation

public function participants()
{
    return $this->hasMany(Participant::class);
}

public function messages()
{
    return $this->hasMany(‘App\Chat\Message’);
}

User

public function messages()
{
    return $this->morphMany(Message::class, ‘sender’);
}

public function conversations()
{
    return $this->hasMany(Conversation::class);
}

public function participants()
{
    return $this->belongsToMany(Participant::class);
}

Client

public function messages()
{
    return $this->morphMany(Message::class, ‘sender’);
}

public function conversations()
{
    return $this->hasMany(Conversation::class);
}

public function participants()
{
    return $this->belongsToMany(Participant::class);
}
0 likes
2 replies
douglasakula's avatar

Looks good - though you will need pivot tables in your database design - for cases where you have many to many relationships

faa's avatar
Level 3

Hi @douglasakula

Thanks a lot for you comment!, so my Participant would be a Morph pivot table, right?

Please or to participate in this conversation.