Carlos F
Carlos F

Reputation: 4981

Laravel verify if relation between many to many exist

Using Laravel 5.5

Lets say I have a User table and Conversation table which are on a ManyToMany relation.

Users

id user

1 A

2 B

3 C

4 D

Conversation

id title

1 Conv1

2 Conv2


Users A, B and C are associated to Conv1

Users B, C and D are associated to Conv2.

If the user wants to create a new Conversation and chooses A,B and C

How can I verify that a Conversation with these and only these users already exists?


public function postThread() {
    $thread = new Thread;
    $thread->title = request()->get('name');
    $thread->type = request()->get('type');
    /* How to verify if Thread exists with and only with all the users in request()->get('users') */
    Auth::user()->threads()->save($thread); //creates relation with new thread
    foreach (request()->get('users') as $user) {
        $user = User::find($user);
        $user->threads()->save($thread);//creates relation with every user    with new thread
    }
    $thread->save();
    return $thread;
    } 

Upvotes: 1

Views: 319

Answers (1)

gbalduzzi
gbalduzzi

Reputation: 10186

Can't test it right now, but should work (still not very efficient)

$users = $request->get('users');
$user = Auth::user();
$validThreads = $user->threads()->whereHas('users', function($query) use ($users){
   foreach( $users as $user_id) {
      $query->where('user_id',$user_id);
   }
});
// Valid threads is a collection of threads where all the users are present, now we need to check that no more users are present in that thread
$totalUsers = count($users)+1;
$thread = $validThreads->filter(function($thread) use ($totalUsers){
    return $thread->users()->count() == $totalUsers;
})->first();

if (is_null($thread)) {
    // The thread does not exists
}

Upvotes: 1

Related Questions