2

I don't know how to explain this in English but i will try my best .

I have a table called invoices and when a user does something a record is added to the table . which is called Amount .So i want to know is it possible to add all the records that enters the invoice table ?

like :


AMOUNT 1 + AMOUNT 2 + AMOUNT 3 + Keeps going ...


And display the total .

I have no idea what to try and what to do . I never did something like this before

is it possible to accomplish this ?

  • You mean like some sort of SUM DB function? Most (if not all) databases already provide that. – Jonnix Aug 25 '19 at 22:34

3 Answers3

1

It's called Aggregates

Laravel Documentation / Aggregates

a simple example :


$users = DB::table('transactions')
    ->sum('transactions.amount');


if you are trying to sum a relationship try something like this :


$user->invoices->sum('amount')


Laravel Eloquent Sum of relation's column

Alan
  • 386
  • 1
  • 3
  • 17
1

You could make it easy using sum() like this one

invoice::sum('amount');

you can check laravel docs

Joseph
  • 5,644
  • 3
  • 18
  • 44
0

You could use Eloquent with your model:

$total = Invoice::where('column', 'some condition')->sum('amount');

You could use DB builder:

$total = DB::table('invoices')->sum('amount');

In a relationship

Sale::where('column', 'some condition')->with('invoices', function($query){
    $query->sum('amount');
}])->get();

You could use sql

SELECT SUM(amount) as Total FROM invoices WHERE ...... some condition

is that what you need?

Ezequiel Fernandez
  • 954
  • 11
  • 18