1
votes

i'm trying to achieve a private messaging system in Laravel but i'm stuck by checking if a conversation exist.

I have 3 Tables:

conversations
- id

users
- id
- name
- etc

conversation_user (pivot)
- user_id
- conversation id

My model Conversation belongsToMany Users and User belongsToMany Conversations.

Adding a conversation and attaching the users to the pivot table is working fine but i don't find a clean way to check if a conversation between 2 users exist.

I appreciate any help.

Ben

2

2 Answers

1
votes

Try the following query and see if it will help you:

Conversation::whereHas('users', function($query) use ($userIds) {
    $query->whereIn('id', $userIds);
})->exists();
0
votes

use @ruffles answer with some little changes:

$hasConversation = Conversation::whereHas('users', function($query) use ($userIds) {
    $query->whereIn('id', $userIds);
})->count() === 2;