title: How can I update pivot table on laravel?
body: <p>I use laravel 5.3</p>
  
  <p>I have 3 table : table product, table category and table products_categories</p>
  
  <p>table product : id, name, etc</p>
  
  <p>table category : id, name, etc</p>
  
  <p>table products_categories : id, product_id, category_id</p>
  
  <p>In model product, I have method this :</p>
  
  <pre><code>public function categories()
  {
      return $this-&gt;belongsToMany(Category::class, 'products_categories', 'product_id', 'category_id')
                  -&gt;withPivot('id')
                  -&gt;withTimestamps();
  }
  </code></pre>
  
  <p>So 1 product have many category</p>
  
  <p>My code like this</p>
  
  <p>For example $param['category'] like this :</p>
  
  <blockquote>
    <p>Array (
        ['category1'] => 4
        ['category2'] => 11
        ['category3'] => 18 )</p>
    
    <p>$product_id = 1</p>
  </blockquote>
  
  <pre><code>foreach ($param['category'] as $category) {
      Product::find($product_id)
          -&gt;categories()
          -&gt;attach(
              $category, 
              []
          );
  }
  </code></pre>
  
  <p>It used to add category on the pivot table and it works</p>
  
  <p>But if I update category on the pivot table, it does not work</p>
  
  <p>I try like this :</p>
  
  <p>For example the category previously edited like this</p>
  
  <p>$param['category'] = </p>
  
  <blockquote>
    <p>Array (
        ['category1'] => 5
        ['category2'] => 12
        ['category3'] => 19 )</p>
    
    <p>$product_id = 1</p>
  </blockquote>
  
  <p>And the code to update data on the pivot table like this :</p>
  
  <pre><code>foreach ($param['category'] as $category) {
      Product::find($product_id)
             -&gt;categories()
             -&gt;wherePivot('product_id', $product_id)
             -&gt;updateExistingPivot($category, ['category_id' =&gt; $category]);
  }
  </code></pre>
  
  <p>It did not update the field category successfully</p>
  
  <p>How can I solve it?</p>