How to get records using whereHas if child has no NULL value in Laravel

Viewed 583

I'm using whereHas and I only want to return the records if sub query has no NULL

return App\Bill_of_Lading::with('transactions.confirmed_transaction.delivery_order')
    ->whereHas('transactions.confirmed_transaction.delivery_order', function ($query) {
        $query->whereNotNull('date_delivered');
    })->get();

Expected result: NULL (because there are delivery orders that have NULL date_delivered) Result: The collection of Bill of Ladings together with the delivery orders with NULL values

I also used Laravel's "with" with no success

return App\Bill_of_Lading::with(['transactions.confirmed_transaction.delivery_order' => function($query){
        $query->whereNotNull('date_delivered');
    }])->get();

I even wrapped the whereNotNull inside where

return App\Bill_of_Lading::with('transactions.confirmed_transaction.delivery_order')
    ->whereHas('transactions.confirmed_transaction.delivery_order', function ($query) {
        $query->where(function($q){
            $q->whereNotNull('date_delivered');
        });
    })->get();
1 Answers

You are almost there, whereHas() has extra parameters for the query conditions. So check if the relationship has null fields and assert it to be 0, therefor no delivery order columns can be null.

->whereHas(
    'transactions.confirmed_transaction.delivery_order', function ($query) {
        $query->whereNull('date_delivered');
    },
    '=',
    0
)
Related