0

I am working on small finance web app and I need to generate one monthly general report of all the users which shows a total of all the transactions made by each user during a month. the table structure is as below.

username    amount  date
-----------------------------
a           1000    2018-8-1
b           2000    2018-8-1
c           1500    2018-8-3
b           1700    2018-8-6
b           1100    2018-8-7
a           2000    2018-8-10
c           1600    2018-8-12           

Need to get sum of each user's transactions during the month such as

a : 3000
b : 4800
c : 3100

Please help me to find out the sum using laravel query builder.

HirenMangukiya
  • 645
  • 3
  • 13
  • 30

1 Answers1

-1

You can do this :

$user
->transactions()
->where('date', '>', Carbon::before())
->where('date', '<', Carbon::now())
->get(['user_id', 'amount'])
->sum('amount');

This considering you have a relationship between transactions and user models. You can adapt to your schema. But the pure MySQL solution that @Tim Biegeleisen linked may be more resources efficient.

You may also use whereBetween(), but check that it works correctly with dates.

Mtxz
  • 3,749
  • 15
  • 29