title: Laravel avoid duplicate entry in child table
body: <p>I have product which has many barcodes, when I'm in product edit page and I add/remove/edit barcodes of product it saves barcodes all over again (PS: I am aware where the issue comes from, but not sure about the solution for it)</p>
  
  <h1>Logic</h1>
  
  <p>So here is what I expect to happen when i'm in product edit page:</p>
  
  <ol>
  <li>If current barcodes has changed just update them</li>
  <li>if any of current barcodes removed, delete them from database</li>
  <li>if any new barcode added to the list, add it in database</li>
  </ol>
  
  <blockquote>
    <p>Basically is <code>sync()</code> functionality that i'm looking for, but based on my model relationships i think using <code>sync()</code> is not an option.</p>
  </blockquote>
  
  <h1>Code</h1>
  
  <p><code>Product model</code></p>
  
  <pre><code>public function barcodes()
  {
      return $this-&gt;hasMany(Barcode::class, 'product_id', 'id');
  }
  </code></pre>
  
  <p><code>barcode model</code></p>
  
  <pre><code>protected $fillable = [
      'product_id', 'serial_number',
  ];
  
  public function product()
  {
      return $this-&gt;belongsTo(Product::class);
  }
  </code></pre>
  
  <p><code>Controller (update function)</code></p>
  
  <pre><code>public function update(Request $request, $id)
  {
      $product = Product::find($id);
      $product-&gt;name = $request-&gt;input('name');
      if($product-&gt;save())
      {
          if(!empty($request-&gt;input('barcodes')))
          {
              foreach($request-&gt;input('barcodes') as $bb)
              {
                  if(!empty($bb['serial_number'])){ // make sure no empty value saves
                      $barcode = new Barcode;
                      $barcode-&gt;product_id = $product-&gt;id;
                      $barcode-&gt;serial_number = $bb['serial_number'];
                      $barcode-&gt;save();
                  }
              }
          }
      }
  }
  </code></pre>
  
  <blockquote>
    <p>As I mentioned above <code>I am aware where the issue comes from, but not sure about the solution for it</code> and the issue of duplicate saving data is that I'm using <code>$barcode = new Barcode;</code>.</p>
  </blockquote>
  
  <h1>Extra</h1>
  
  <p>In order to be clear, this is what my data looks like when I send update request to back-end</p>
  
  <p><a href="https://i.stack.imgur.com/XyvFt.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/XyvFt.png" alt="one"></a></p>
  
  <h1>Question</h1>
  
  <p>What should I change in my code in order to achieve my desire logic?</p>