Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Attach extra attributes to Laravel pivot table

I have 4 extra attributes ('product_id', 'quantity', 'discount_percent', 'discount_amount') in my pivot table, but my values for these are always 0 when I store, while the rest is populated properly. Any ideas?

Invoice model

public function productversion()
{
    return $this->belongsToMany('App\Productversion')->withPivot('product_id', 'quantity', 'discount_percent', 'discount_amount')->withTimestamps();
}

Productversion model

public function invoice()
{
    return $this->belongsToMany('App\Invoice')->withPivot('product_id', 'quantity', 'discount_percent', 'discount_amount')->withTimestamps();
}

Controller (store)

$invoice->productversion()->attach($productversionid, ['product_id' => $productid], ['quantity' => $qty], ['discount_percent' => $discountprc], ['discount_amount' => $discountamt]);
like image 596
user3489502 Avatar asked Aug 26 '16 15:08

user3489502


2 Answers

Just one array will do:

$invoice->productversion()->attach($productversionid, [
  'product_id' => $productid,
  'quantity' => $qty,
  'discount_percent' => $discountprc,
  'discount_amount' => $discountamt
]);
like image 117
Jeff Avatar answered Sep 28 '22 20:09

Jeff


In addition to @jeff's method, you can attach or sync multiple elements with pivot attributes providing a multidimensional array that has ids as keys.

$attach_data[$productversionid] = [
    'product_id'       => $productid,
    'quantity'         => $qty,
    'discount_percent' => $discountprc,
    'discount_amount'  => $discountamt
];

Then you can $invoice->productversion()->attach($attach_data).

Substantially you can pass an array like

[
    'relation_id' => [
        // pivot data
    ],
    'relation_id' => [
        // pivot data
    ],
    // ...
]
like image 39
phaberest Avatar answered Sep 28 '22 20:09

phaberest