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: 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 :
incomes +----+---------+-------+ | 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.
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.
You can get the sum using this
$money = DB::table('incomes')->sum('money');
Check this link https://laravel.com/docs/5.0/queries