Sunday, April 16, 2017

Laravel 5.4 - use a custom attribute model in a collection

  • I have the model Order.
  • Order has many Item.
  • An Item has a price attribute (from the database).
  • An Order has a getAmountAttribute method which looks like this:

/**
 * @return double
 */

public function getAmountAttribute()
{
    return $this->items->sum('price');
}


/**
 * @return \Illuminate\Database\Eloquent\Relations\HasMany
 */
public function items()
{
    return $this->hasMany(Item::class);
}

So I can fetch the total price of order's items by simply doing $order->amount.


Now I have a collection of Order and I want to fetch every order that its total price starts at 10. How can I achieve that since I can't use my custom attribute on a where statement?



via Eliya Cohen

Advertisement