Laravel Eloquent sum throwing error

I’m just simply want to sum column .
I used this code

$money = Income::sum('money');

also tired this
$money = Income::select(DB::raw('sum(money)'))->get();

but it’s throwing error . I’m using postgresql as my database .
Error message :
SQLSTATE[42883]: Undefined function: 7 ERROR: function sum(character varying) does not exist
LINE 1: select sum("money") as aggregate from "incomes"
HINT: No function matches the given name and argument types. You might need to add explicit type casts. (SQL: select sum("money") as aggregate from "incomes")

my table :

| id | orderid | money |
|  1 |    2343 |    23 |
|  2 |    2344 |    55 |


Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

According to your error message, the sum method doesn’t take in a varchar (character varying). It sounds like the money column is not a number datatype (though it my solely consist of numeric values.

To work around this, cast the value to a numeric data type:

Income::select(DB::raw('sum(cast(money as double precision))'))->get()

Note that this will not necessarily be performant. You may consider changing the database schema (if possible) to store money as an integer and as cents in the database. That is, 1000 in the database would reflect $10.00.

Method 2

You can get the sum using this

$money = DB::table('incomes')->sum('money');

Check this link

All methods was sourced from or, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Notify of

Inline Feedbacks
View all comments
Would love your thoughts, please comment.x