Ad

Access Index Of Pivot Table In Laravel

- 1 answer

Is there a way that i can Access pivot table like below???

array:18 [
  "id" => 4
  "user_id" => 5
  "price" => 8659
  "created_at" => "2020-01-17 14:08:06"
  "updated_at" => "2020-01-17 14:08:06"
  "pivot" => array:5 [
    "purchase_id" => 6
    "product_id" => 4
    "quantity" => "13"
    "unit_price" => "3212"
    "discount" => "11.00"
  ]
]

I want to Update Pivot Table and i tried method like below

       foreach($request->products as $product) {
            $purchase->products()->updateExistingPivot($product['id'], [
                'unit_price' => $product['unit_price'],
                'quantity' => $product['quantity'],
                'discount' => $product['discount'],
            ]);

            // dd($product);
        }

But got an error message: "Undefined index: unit_price".

Any Help, Thanks in Advance...

Ad

Answer

It seems you don't have unit_price key in your $product,

Try to call it by $product['pivot']

$purchase->products()->updateExistingPivot($product['id'], [
                'unit_price' => $product['pivot']['unit_price'],
                'quantity' => $product['pivot']['quantity'],
                'discount' => $product['pivot']['discount'],
            ]);
Ad
source: stackoverflow.com
Ad