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

alev's avatar
Level 4

query the lowest value for each day in the past 30 days in a table

I am saving prices for a product several times every day in a price table.

Now, I would like to collect data for a chart with the lowest prices for each of the past 30 days for one specific product. Is there a way to do this in Eloquent?

I have no other idea than creating a query for each day. But I have the feeling this probably can be done a lot better.

Any idea?

0 likes
4 replies
MichalOravec's avatar

@alev You can do something like

$start = now()->subDays(30);

for ($i = 0; $i <= 30; $i++) {
    $days[] = $start->copy()->addDays($i)->toDateString();
}

$monthLabels = collect($days);

$month = Price::selectRaw('created_at as day, min(price) as price')->where('product_id', $product->id)->groupBy('day')->latest('day')->get()->mapWithKeys(function ($item) {
    return [$item['day'] => $item['price']];
});

$prices = $monthLabels->map(function ($day, $key) use ($month) {
    return $month->get($day, 0);
});

But I don't know your models and table structure, but propably it could help to you.

1 like

Please or to participate in this conversation.