Laravel – How to get SUM of a column in database table
Laravel have DB class to perform raw queries whenever needed instead of Eloquent model. I recommend to use eloquent model in most cases but sometimes we need to perform raw queries. DB class is where we need.
Getting sum of a column in database is fairly simple. See below use case with and without where clause.
$amount = DB::table('invoice_details')
->sum('billing_amount');
which gets the sum of the entire column. I tried writing:
$amount = DB::table('invoice_details')
->where('invoice_id' '=' $id)
->sum('billing_amount');
Make sure SUM method is placed at the end otherwise Laravel may thrown an error.
Recent Comments