Laravel 5.4 - use custom attribute model in collection

  • I have a model Order

    .
  • The order has a lot Item

    .
  • An Item

    has an attribute price

    (from the database).
  • Order

    has a getAmountAttribute

    method that 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 get the total cost of the order items simply by doing $order->amount

.


Now I have a collection Order

and I want to get every order when the total price starts at 10. How can I achieve this since I cannot use my own attribute in the statement where

?

+3


source to share


2 answers


you can do it via ->havingRaw('SUM(price) > 10')



0


source


You can get only the desired collection of orders (orders with a total value of 10 or more) instead of getting the entire collection of orders and getting the orders you want.



->get(function($order) {
        return $order->amount > 10;
    });

      

0


source







All Articles