david001's avatar

Laravel message system table and relationship

Hi, I have table conversations with attribute id,user_id,receiver_id, text,created_at,updated_at.

I want to get list of users from this table who has a conversations and the user name should not be repeated. For example user_id: 1John send message to receiver_id :2, David. Now when John logged in, he should see David name in chat page as he sent message to David. Similarly , when David logged in , he should see John name in his chat page because he received message from john.

My table has structure like this: User id: 1, receiver id:2 ,text:hi User id: 1, receiver id: 2 ,text: how are you?

User id:2, reciver id:1, text: I am fine.

Now when i loggedin as one user, either david or john and when i have to see list of users whom I have send messages or from whom I got massages I will get duplicates user(same user name printed multiple times) because of same user_id or receiver_id.

My question is, what should be the query so that i don't get same name repeated in my chat page multiple times? Should i design a different table structure for this? If so what should be table structure and relationship? My two models are:

User.php and Conversation. php

Method in controller.


Public function  getUser(){
 $users=User::get();
return view ('chat',compact('users');

Any help would be highly appreciated.

0 likes
5 replies
MostafaGamal's avatar
Level 10

try this:

in your Conversation.php

public function sender() {
	return $this->belongsTo('App\Models\User', 'user_id')
}

public function receiver() {
	return $this->belongsTo('App\Models\User', 'receiver_id')
}

in your controller:

$conversations = DB::table('conversations')
									->where('user_id', auth()->id())
									->orWhere('receiver_id', auth()->id())
									->get()

$users = $conversations->map(function($conversation){
	if($conversation->user_id === auth()->id()) {
		return $conversation->receiver;
	}
	return $conversation->sender;
})->unique();

return view ('chat',compact('users');
1 like
Zeeshan1998's avatar

@MostafaGamal what will be the solution if there are two different roles with a different table like system manager and user, how will we define sender and receiver relation in the conversation.php model. i currently developing a system like this and would appreciate your help.

Please or to participate in this conversation.