It seems like there might be a misunderstanding of how the filter method works in combination with the where method on a Laravel collection. The filter method expects a closure that returns a boolean value to determine if an item should be included in the resulting collection. However, in the provided code, the closure is returning a collection (or a builder) from the where method calls, which is truthy even if it's empty, so the filter isn't actually filtering anything out.
To fix this, you should return a boolean from the closure by checking if the collection returned by the nested where calls is not empty. You can use the isNotEmpty method for this purpose.
Here's the corrected code:
$relatedOrder = $orders->where('id', $uniqueID)
->filter(function ($order) use ($txid) {
// Check if the order has any transactions that match the criteria
return $order->orderTransactions
->where('txid', $txid)
->where('is_confirmed', false)
->isNotEmpty(); // This will return true if there's at least one transaction matching the criteria
});
With this change, the filter method will correctly include only those orders that have at least one transaction with the specified txid and where is_confirmed is false.