Home > Software engineering >  How can I get total sum of every customers paid amount in Laravel ??
How can I get total sum of every customers paid amount in Laravel ??

Time:09-01

I'm trying to get highest paid amount from my laravel app. From my payments table I want to use customer_id & paid_amount for calculating hightest paid amount but my code isn't working expected! please see my code snippet below

N.B: I want to get all columns of payments table, but how I can do that?

$payments = Payment::with(['customer'])
                        ->select(DB::raw('sum(paid_amount) as paid_amount, customer_id'))
                        ->orderBy('customer_id', 'DESC')
                        ->paginate(10); 

Also I've tried this one but this times it shows me an error because I was using relations with Customer model!

$payments = Payment::select(DB::raw('sum(paid_amount) as paid_amount, customer_id'))
                        ->groupBy('customer_id')
                        ->paginate(10);

CodePudding user response:

Here is the solution if you want to do it with pagination and relationship.

Payment::query()
->select(DB::raw("sum(paid_amount) as paid_amount, customer_id"))
->with(['customer'])
->groupBy('customer_id')
->orderBy('customer_id', 'DESC')
->paginate(10)

CodePudding user response:

You can try the query this way to get SUM.

Payment::query()
->select(DB::raw("sum(paid_amount) as paid_amount, customer_id"))
->with(['customer'])
->groupBy('customer_id')
->orderBy('customer_id', 'DESC')
->get();
  • Related