3

I have many to many relation between Order and Product. Pivot table order_product has additional columns: price, quantity. I have custom pivot class:

class OrderProduct extends Pivot
{
    protected $attributes = ['price', 'quantity'];

    public function getPriceAttribute($value)
    {
        return number_format($value, 2);
    }

    public function setPriceAttribute($value)
    {
        $price = $value - ($value * 0.1);
        $this->attributes['price'] = $price;
    }    
}

class Product extends Model
{
    public function orders()
    {
        return $this->belongsToMany(Order::class, 'order_product')->using('App\Models\OrderProduct')->withPivot('price','quantity');
    }
}

Accessor works but mutator doesn't.
How to make mutator setPriceAttribute working with sync(), attach()?

$value is correct in setPriceAttribute, but modifications are not applied in DB?

vpalade
  • 1,427
  • 1
  • 16
  • 20
  • 1
    here is a link that will explain this https://stackoverflow.com/questions/28921787/accessors-getter-mutators-setter-on-a-pivot-table-in-laravel – Sohel0415 Feb 27 '18 at 11:40

1 Answers1

2

Implement the mutators and accessors in relevant Models.

class Product extends Model
{




  public function getPriceAttribute($value)
   {
    return number_format($value, 2);
   }

  public function setPriceAttribute($value)
  {
    $price = $value - ($value * 0.1);
    $this->attributes['price'] = $price;
  } 
  public function orders()
   {
     return $this->belongsToMany(Order::class, 'order_product')->using('App\Models\OrderProduct')->withPivot('price','quantity');
   }
}

Hope this helps

FULL STACK DEV
  • 15,207
  • 5
  • 46
  • 66