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
This is my Message Schema :
Schema::create('messages', function (Blueprint $table) {
$table->increments('id');
$table->unsignedBigInteger('sender_id');
$table->unsignedBigInteger('receiver_id');
$table->foreign('sender_id')->references('id')->on('users');
$table->foreign('receiver_id')->references('id')->on('users');
$table->text('message')->nullable();
$table->timestamps();
});
I would like to fetch a list of users with who I'm talking ( who contacted me first or who I contacted first ) Just like Facebook Inbox, Left side you see always people who contacted you or who you contacted first
Thank you
CodePudding user response:
If we look at the situation from user's perspective, I guess it makes sense if the relationship is considered as one to many:
Message Model
public function user()
{
return $this->belongsTo(User::class);
}
User Model
public function user_chats()
{
return $this->hasMany(Message::class);
}
I (the user) have multiple messages and every message belongs to me (the user).
CodePudding user response:
Assuming your relationship is defined correctly, you should be able to call this to get what you need:
auth()->user()->user_chats->unique()
->user_chats or ->user_chats()->get() (same code, one is a shortcut) will return a Collection, and you can call any Collection method on it, like unique() to filter out duplicates:
