0

I want to update pivot table in laravel 8 .I'm trynig sync method, but only insert first item of an array.

Here is my code

         foreach ($products as $product) {
            $quantity        = $product['quantity'];
            $product_id      = $product['product_id'];
            $food_item_price = FoodItemPrice::where('food_item_id', $product_id)->first();
          
            $order->orderFoodItems()->sync([$product_id => [
                'quantity'           => $quantity,
                'food_item_price_id' => $food_item_price->id,
            ]]);
        }

In $products may have many products, but with sync method, it only updates first product. How to update pivot table properly?

ihprince
  • 147
  • 1
  • 2
  • 17
  • [the documentation](https://laravel.com/docs/8.x/eloquent-relationships#syncing-associations) says that this is how it's supposed to work. I think you need `syncWithoutDetaching` to not dettach previously attached relationships – apokryfos Apr 19 '21 at 07:26
  • https://stackoverflow.com/a/30351384/8158202 Check this comment. This contains solution to your problem. – Akhzar Javed Apr 19 '21 at 07:42
  • Problem has solved. I simply changed my code to this $data[ $product_id] = [ 'quantity' => $quantity, 'food_item_price_id' => $food_item_price->id, ]; $order->orderFoodItems()->sync($data); – ihprince Apr 19 '21 at 11:42

0 Answers0