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;
}