I have a task to apply a discount, on every 10th order for customer starting from the beginning of their subscription, data is coming from an API call outside of Laravel.
e.g
[
[
order_id: xxxxx,
details: [
],
customer_id: xxxxx
],
[
order_id: xxxxx,
details: [
],
customer_id: xxxxx
],
]
The criteria for the order to be included in the count, is to have a status of SUCCESS. What I did was to loop through all orders that have a status of SUCCESS, and create a counter starting from 1, and if the counter hits 10, I will reset the counter again to the start, until I've looped through all orders and the last number that was recorded is the current Nth order from the customer, so if the current Nth order is 9, then the succeeding order would be applied with a discount.
However this seems inefficient and if the customer has a lot of orders, the code will take time just to loop and go through all orders, to get what Nth order position is currently for the customer. Is there a formula to get what the current Nth order position is ? Or I can use collections, chunk the array by 10 and get the last group and from there I just loop them to get the Nth position of the latest order ? Any advice would be appreciated. Thank you.
Edit due to not being in the database but an api response.
$applicable_for_discount = collect($data)->filter(function ($item) {
return $item['successful'];
})->chunk(9)->last()->count() === 9;