Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

gives error: Indirect modification of overloaded property

like image 595
AxlSmith Avatar asked Jun 26 '14 08:06

AxlSmith


People also ask

How do I update a pivot table in Laravel?

There are many ways to update the pivot table in Laravel. We can use attach(), detach(), sync(), and pivot attribute to update the intermediate table in Laravel.


1 Answers

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.

like image 62
Jarek Tkaczyk Avatar answered Sep 26 '22 19:09

Jarek Tkaczyk