laravel collection nested "where"

857 Views Asked by At

Assume the following collection:

 [
   order
    -id
    -receiverAddress
    -...
    relations
        transactions
            -id
            -transaction_id_external
            - ...
 ]

I tried to use the following filter on the collection:

    $isNotEmpty = $orders->filter(function ($order) use ($receivedPaymentDetails) {
        return $order->transactions
            ->where('transaction_id_external', $receivedPaymentDetails->txid)
            ->where('order.receiverAddress', $receivedPaymentDetails->address)
            ->isNotEmpty();
    })->isNotEmpty();

It seems like this doesn't work, any idea how I can filter on the parent collection item order.receiverAddress?

1

There are 1 best solutions below

5
On

Since you want to filter based on the transactions relations, you must perform some form of join query with your transactions table

Easiest way for you would be to place your queries in a whereHas callback

$isNotEmpty = $orders->filter(function ($order) use ($receivedPaymentDetails) {
            return $order->whereHas('transactions', function ($query) use ($receivedPaymentDetails) {
                $query->where('transactions.transaction_id_external', $receivedPaymentDetails->txid);
                $query->where('order.receiverAddress', $receivedPaymentDetails->address);
            })
                ->isNotEmpty();
        })->isNotEmpty();