title: Laravel get conversation where users in array
body: <p>I am making a messaging app, and i need to check if a conversation already exists that has a certain list of users (no more, no less). I have this model:</p>
  
  <pre><code>class Conversation{
      public function users(){
          return $this-&gt;belongsToMany('App\User');
      }
      public function messages(){
          return $this-&gt;hasMany('App\Message');
      }
  
  }
  </code></pre>
  
  <p>I have these tables:</p>
  
  <p>conversations:</p>
  
  <ul>
  <li>id</li>
  <li>user_id &lt;- the owner of the conversation</li>
  </ul>
  
  <p>users:</p>
  
  <ul>
  <li>id</li>
  <li>email</li>
  <li>password</li>
  </ul>
  
  <p>conversation_user:</p>
  
  <ul>
  <li>id</li>
  <li>conversation_id</li>
  <li>user_id</li>
  </ul>
  
  <p>I want to make a post request like this:</p>
  
  <pre><code>{
     "users": [1,4,6], &lt;- user ids
     "message": "Some message"
  }
  </code></pre>
  
  <p>If a conversation already exists with all and only users 1,4,6, the message should be added to that conversation to avoid having duplicate conversations in the database. Otherwise i will make a new conversation with the specified users.
  This is the best i have been able to do so far:</p>
  
  <pre><code>$existing_conversation = $user-&gt;conversations()-&gt;whereHas('users', 
      function($query) use ($data){
          $query-&gt;whereIn('user_id', $data['users']);
      }
  )-&gt;has('users', '=', count($data['users'])); 
  </code></pre>
  
  <p>But it just returns the conversations that has exactly the amount of users that was in the users array. It ignores the inner query..</p>
  
  <p>Does anyone have an idea for this? :)</p>