AxlSmith
AxlSmith

Reputation: 243

How can I set value for extra field on Eloquent pivot table

$recourse->pivot->field = 'value';

gives error: Indirect modification of overloaded property

Upvotes: 6

Views: 9107

Answers (3)

Darmen Amanbay
Darmen Amanbay

Reputation: 4881

For Laravel 5, you may want to use this syntax:


$order->products()->attach($product, ['quantity' => 100]);

Where quantity is an attribute of pivot table.

Upvotes: 0

Carlo V
Carlo V

Reputation: 41

You should save() the pivot itself.

$order->pivot->price = '1.234';
$order->pivot->save();

Upvotes: 0

Jarek Tkaczyk
Jarek Tkaczyk

Reputation: 81187

pivot is available only in the context of a relation:

// won't work
$model = Model::first();
$model->pivot; // null

// will work
$anotherModel = AnotherModel::first();
$relatedModel = $anotherModel->relation()->first();
$relatedModel->pivot; // Pivot object

But for what you are trying to do simply use additional param in the save method:

$product = Product::find($item->id);
$order->product()->save($product, ['price' => 12.34]);

For existing relation:

$product = $order->product()->find($productId);
$product->pivot->price = 12.34;
$product->pivot->save();

// or
$order->product()->updateExistingPivot($productId, ['price'=>12.34]);

And I suggest you use products for that kind of relation in order to make it easier to read.

Upvotes: 17

Related Questions