Laravel relationships attach if not already attached : <p>Is there a quick way of attaching relationships if they're not already attached. I am using this code to update relations of a model;</p>

<pre><code>        if (!empty($request-&gt;get('roles')) &amp;&amp; is_array($request-&gt;get('roles'))) {
            $message-&gt;Roles()-&gt;attach($request-&gt;get('roles'));
        }
        if (!empty($request-&gt;get('users')) &amp;&amp; is_array($request-&gt;get('users'))) {
            $message-&gt;Users()-&gt;attach($request-&gt;get('users'));
        }
</code></pre>

<p>But I am getting this error which I am this error;</p>

<blockquote>
  <p>SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '1-41' for key 'PRIMARY' (SQL: insert into <code>message_user</code> (<code>message_id</code>, <code>user_id</code>) values (1, 41), (1, 42), (1, 43), (1, 44), (1, 45), (1, 46), (1, 47), (1, 48), (1, 49), (1, 50))</p>
</blockquote>

<p>I want to avoid going through a very long list of array check which users are not already attached and attaching them. Also let me know if this is the only way.</p>

<p>I am thinking something like;</p>

<pre><code>$message-&gt;Users()-&gt;attachIfNotAttached($request-&gt;get('users'));
</code></pre>
