I don't really understand why you need a user_chats table with user_id and contact_id fields.
I'm getting duplicated rows
I'm working on a small project (Internal Messaging System) using Laravel, I would like to get a list of users with who I'm talking.
I have 2 Models, User, Message and an intermediate Table called user_chats
Schema::create('user_chats', function (Blueprint $table) { $table->unsignedBigInteger('user_id'); // Auth::user()->id $table->unsignedBigInteger('contact_id'); // user who you chatted with either way $table->foreign(user_id')->references('id')->on('users'); $table->foreign('contact_id')->references('id')->on('users'); });
And I have a many to many relationship in my User model:
public function user_chats() { return $this->belongsToMany(User::class, 'user_chats', 'user_id','contact_id'); }
I'm fetching the list of users with who I'm talking like that :
Auth::user()->user_chats;
The problem is I'm getting duplicated rows, for example I contacted you and you contacted me back (same conversation) I should get only one row (your name) . But I'm getting result twice because I contacted you and you contacted me back. I need only one row contain your name. like Facebook inbox, left side you see only people who you contacted or they contacted you.
Thank you
to get the users;
$ids= Message::query()
->select('user_id', 'receiver_id')
->where('user_id', Auth::id())
->orWhere('receiver_id', Auth::id())
->get()
->map(function($message) {
return $message['user_id'] == Auth::id()
? $message['receiver_id']
: $message['user_id'];
})
->unique();
$users = User::whereIn('id',$ids)->get();
Please or to participate in this conversation.