1
votes

Is there a better way to get the object with the lowest price with Laravel Eloquent? Each Product has several ticketTypes and each ticketType can have multiple prices.

    public function includeLowestPrice(Product $product)
    {

    $lowestPriceTicket = null;

    foreach ($product->ticketTypes()->hasActivePrices()->get() as $type) {
        foreach ($type->prices()->get() as $ticketPrice) {
            if (!$lowestPriceTicket || $ticketPrice->value < $lowestPriceTicket->value) {
                $lowestPriceTicket = $ticketPrice;
            }
        }
    }

    return $lowestPriceTicket ? $this->item($lowestPriceTicket, new TicketPriceTransformer()) : null;
    }
1

1 Answers

7
votes
$product->ticketTypes()->hasActivePrices()->orderBy('price')‌​->first() 

Will get the lowest priced product assuming price is the name of the field and hasActivePrices is a query scope that returns the Eloquent Query Builder.

first() will return the first model instead of a collection, and orderBy() will sort the query