title: Eloquent save many to many relation without duplicates
body: <p>I'm using Laravel 5.5 and have a many to many relationship between <em>products</em> and <em>tags</em>, with a pivot table that has <code>product_id</code> and <code>tag_id</code> as the only two columns.</p>
  
  <p>My models look as follow:</p>
  
  
  
  <pre class="lang-php prettyprint-override"><code>class Product extends Model
  {
      public function tags()
      {
          return $this-&gt;belongsToMany( 'App\Tag' );
      }
      // other code
  }
  </code></pre>
  
  <p>and</p>
  
  <pre class="lang-php prettyprint-override"><code>class Tag extends Model
  {
      public function product ()
      {
          return $this-&gt;belongsToMany( 'App\Product' );
      }
  
      protected $fillable = [ 'slug' ];
  }
  </code></pre>
  
  <p>The tags table has <code>id</code>, <code>slug</code> and the timestamps columns. I am trying to assign tags that I'm getting from a form in a comma separated string to a product with the code below:</p>
  
  <pre class="lang-php prettyprint-override"><code>$tags_r = explode( ',', $request-&gt;tags );
  
  $tags = [];
  
  foreach ( $tags_r as $tag ) {
      $tags[] = new Tag( [ 'slug' =&gt; strtolower( trim( $tag ) ) ] );
  }
  
  $p-&gt;tags()-&gt;saveMany( $tags );
  </code></pre>
  
  <p>My problem is that when I try to save the tags with no constraint on the <code>tags.slug</code> column, I end up with duplicate tags on several rows. When I set the <code>slug</code> column to unique to avoid duplicates the code throws an error complaining about the constraint.
  How do I make it so that if a tag exists, it is assigned to a product by use of the pivot table and it is only added as a new row in the <em>tags</em> table if it doesn't already exist?</p>