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.

Written by Bala Krishna

Bala Krishna is web developer and occasional blogger from Bhopal, MP, India. He like to share idea, issue he face while working with the code.