'Laravel eager load multiple tables with constraints and orderby different columns

I have multiple tables to eager load and I already set the constraints but the problem I have is ordering the transactions by 'payment.initiated' and 'credit_card.transaction_date' I want these two sorted out here's my actual query

$transactions = Transaction::with([
            'payment.fund',
            'payment.campus',
            'credit_card.fund',
        ])
        ->where(function($subQuery){
            $subQuery->whereHas('payment', function ( $query ) {
                $query->where('approved', 1)
                ->whereNull('duplicate')
                ->whereNull('template')
                ->where('initiated', '>=', $this->startDate->toDateTimeString())
                ->where('initiated', '<=', $this->endDate->toDateTimeString());
            })
            ->orWhereHas('credit_card', function ( $query ) {
                $query->where('transaction_date', '>=', $this->startDate->toDateTimeString())
                ->where('transaction_date', '<=', $this->endDate->toDateTimeString());
            });
        })
        ->whereIn('users', $this->users()->toArray())
        ->get();

I want to add an order by for transaction_date and initiated this dates could be null I have the query but I can't get it to work because the payment and credit_card is inside whereHas

ORDER BY CASE
      WHEN initiated IS NULL THEN transaction_date
      WHEN transaction_date IS NULL THEN initiated
      WHEN initiated > transaction_date THEN initiated
      ELSE transaction_date
      END DESC


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source