First of all, you should define the Conversation relationship with messages like this:
Conversation Model
public function messages()
{
return $this->hasMany('App\Message');
}
You should define the inverse relationship as well:
Message Model
public function conversation()
{
return $this->belongsTo('App\Conversation');
}
You could show all conversations by a user with the code below:
public function getConversations($userId)
{
$conversations = Conversation::where('sender_id',$userId)->orWhere('receiver_id',$userId);
return view('yourview', compact('conversations'));
}
In your view you could loop and find every message from every conversation:
@foreach($conversations as $conversation)
@foreach($conversation->messages as $message)
{{$message->message}}
@endforeach
@endforeach
In your conversations
table you could have a user_id
FK, also your relation should look like this:
User Model
public function conversations()
{
return $this->hasMany('App\Conversation', 'user_id');
}
Note: you could use the receiver_id
or sender_id
as a foreign key as well.
With this relation you could get all conversations from a user with this:
$user = User::find($id);
$user->conversations; // This will return all conversations from that user
You could also get all the messages from a user using the Has Many Through relationship:
public function messages()
{
return $this->hasManyThrough('App\Message', 'App\Conversation');
}
Another Approach
Another way to do it is creating a pivot table between users
and conversations
The conversation_user
table
id
user_id
conversation_id
This way a user could have many conversations (Many to many relationship).
You could change your messages
table to:
id
conversation_id
receiver_id
sender_id
content
...
Your Message Model
public function conversation()
{
return $this->belongsTo('App\Conversation', 'conversation_id');
}
The User model
public function conversations()
{
return $this->belongsToMany('App\Conversation');
}
The Conversation Model
public function users()
{
return $this->belongsToMany('App\User');
}
public function messages()
{
return $this->hasMany('App\Message');
}
I think this is the best way to do it
If you wanna get the conversation and the messages:
$user = User::find($id);
foreach($user->conversations as $conversation)
{
foreach($conversation->messages as $message)
{
echo $message->content;
}
}
Another simple way to do it is using the Message Model:
$userMessages = Message::where('receiver_id', $userId)->orWhere('sender_id',$userId)->get();
But this way you will only get the messages, you can find the conversation with this:
foreach($userMessages->conversation as $conversation)
{
echo $conversation;
}