Wednesday, March 1, 2017

Laravel Query Builder - Use sum method on a generated attribute

Let's say I have an Item Model that has:

  • id - Item ID
  • type - The item type
  • is_worthy - Is the item worthy or not.

and I have this method:

public function getPriceAttribute()
{
    return $this->is_worthy ? 100 : 10; // $
}

So far so good.

But! what if I want to sum the price for a collection of items?. I've tried to do this:

App\Item:whereType('..')->sum('price');

But the thing is, that I don't have in my database the column price. Because the price attribute is generated in the Model. So my question is - How can I achieve that?




via Eliya Cohen

Advertisement