Ok i finally managed to get the result by doing this in my controller
$customers = Customer::where('name', 'like', '%' . $name . '%')
->whereHas('payments', function ($query) {
$query->where('payment', 'like', '%unpaid%')
->orWhere('payment', 'like', '%partial%');
})
->select('customers.id')
->join('payments', 'customers.id', '=', 'payments.customer_id')
->addSelect(DB::raw('SUM(payments.unpaid) as unpaid'))
->groupBy('customers.id')
->orderBy('unpaid', 'desc')
->paginate(10);
return new PendingOrderCollection($customers);
and doing this in my Resources
return [
'id' => $this->id,
'name' => ucwords($this->payments->first()->customer->name),
'email' => $this->payments->first()->customer->email,
'payments' => Payment::collection($this->payments),
'unpaidTotal' => Payment::collection($this->payments)->sum('unpaid'),
];
Why i am using the relationship from payments to customers in my resource is because the controller just returns the id and unpaid total ordered by unpaid total, so to get the name and email I used the payment-customer relationship.
This seems not to be an optimised solution, i would be grateful i f someone could help me further optimize this.