Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

SigalZ's avatar

Get lowest value from Pivot table

Using Laravel 10

I have 2 tables:

coffees, bags

I have a pivot table with fields:

bag_id, coffee_id, price

Is there a way to get the lowest price for each coffee?

e.g.

If the table has these values:

bag_id: 1
coffee_id: 1
price: 83

bag_id: 2
coffee_id: 1
price: 320

bag_id: 3
coffee_id: 1
price: 304

I would like some kind of a function on the model that will return the lowest price the coffee has.

$coffee->getLowestPrice() will return 83

Any way to do this?

0 likes
2 replies
gych's avatar
gych
Best Answer
Level 29

Try to use this

class Coffee extends Model
{
    public function bags()
    {
        return $this->belongsToMany(Bag::class)->withPivot('price');
    }

    public function getLowestPrice()
    {
        return $this->bags()->min('price');
    }
}

If you want to follow conventions you could change getLowestPrice to getLowestPriceAttribute

1 like

Please or to participate in this conversation.