I have the following two collections:
$credits = collect([
['quantity' => 3, 'product_id' => 1],
['quantity' => 2, 'product_id' => 5]
]);
$basketItems = collect([
['id' => 1, 'basket_id' => 4, 'product_id' => 1],
['id' => 2, 'basket_id' => 4, 'product_id' => 2],
['id' => 3, 'basket_id' => 4, 'product_id' => 1],
['id' => 4, 'basket_id' => 4, 'product_id' => 1],
['id' => 5, 'basket_id' => 4, 'product_id' => 1]
]);
The $credits
collection tells us the user has 3 available credits to use for product_id
1.
Now I want to create two new collections. If a user has basket items for which they have available credits - this can be determined by the product_id, then I want to add those items into a new collection called $basketItemsUseCredits
.
If the basket items dont have available credits for the type of product, I want to add those items into another collection called $basketItemsPay
.
So in the example above I should end up with $basketItemsUseCredits
with basketitems that have id's 1,3 and 4. $basketItemsPay
should end up with basketsitems that have id's 2 and 5. The following doesn't work.
$basketItemsUseCredits = $basketItems->map(function ($basketItem) use ($credits) {
$qty = $credits->where('product_id', $basketItem->product_id)->get('quantity', 0);
if ($qty > 0) {
// update quantity
$credits->transform(function ($credit) use ($basketItem) {
if ($credit->product_id == $basketItem->product_id) {
$credit->quantity = $credit->quantity - 1;
return $credit;
}
else
return $credit
});
return $basketItem;
}
})
$basketItemsPay = $basketItems->map(function ($basketItem) use ($basketItemsUseCredits) {
if (!$basketItemsUseCredits->contains('id', $basketItem->id))
return $basketItem;
});
if(!$basketItemsPay->isEmpty()) {
// do some extra stuff
}
The following line is always returning 0:
$qty = $credits->where('product_id', $basketItem->product_id)->get('quantity', 0);
Also another thing I've noticed. If $basketItemsPay
is empty e.g. if I dd($basketItemsPay)
I get the following:
Collection {#316 ▼
#items: array:1 [▼
0 => null
]
}
So why does the following always evaluate to true in the above scenario?
if(!$basketItemsPay->isEmpty()) {
// do some extra stuff
}
Any help appreciated.
* UPDATE *
Managed to fix by doing the following - unless any one know a better solution:
$qty = $credits->where('product_id', $basketItem->product_id)->first()['quantity'];
And chaining the reject method as follows to get rid of empty values - does any one know of a more elegant solution?
$basketItemsPay = $basketItems->map(function ($basketItem) use ($basketItemsUseCredits) {
if (!$basketItemsUseCredits->contains('id', $basketItem->id))
return $basketItem;
})->reject(function ($basketItem) {
return empty($basketItem);
});