Can you please properly format the code:
https://help.github.com/en/articles/creating-and-highlighting-code-blocks
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
am new in laravel and I am getting it hard in building difficult queries. I have a project where I need to get which product is most sold for a week or for a month. I have three tables in database: products orders order_items
The table of order_items is attached below.enter image description here
This is the query that I have done to get mos sold product for this week. But I know that is not right. It gets me only the first product.
For example: If I have a order where id = 5 and i have 4 items, it gets me the first one. Also even if the second product has its' quantity more than the first one, it still shows the first product. Can you please help me ?
$most_sold_product_week=Order::join('orders_item','orders.id', '=','orders_item.id_order')
->where('orders.status_order','=','approved')
->whereBetween('orders.created_at', [Carbon::now()->startOfWeek(),Carbon::now()->endOfWeek()])
->select('id_product')
->groupBy('id_product')
->orderByRaw('COUNT(*) DESC')
->limit(1)
->value('id_product');
Please or to participate in this conversation.