Member-only story
Get Sum of Column Values in Laravel with Example
In this tutorial, I will discuss two examples of how to get sum of column values in laravel with the help of laravel query builder. This is very simple and also important if you are working in web development using laravel. Let us take the example one by one below
Also read, How to pass data to all views in laravel
Examples to get sum of column values in laravel
Before getting started with this, we have to create a table in the database. So, let’s create a table
DDL information of the table CREATE TABLE product_info (
Below is the table for your reference
id int(10) NOT NULL AUTO_INCREMENT,
product varchar(255) NOT NULL,
quantity varchar(255) NOT NULL,
price varchar(255) NOT NULL,
created_at timestamp NOT NULL DEFAULT current_timestamp() ON UPDATE current_timestamp(),
updated_at timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
PRIMARY KEY (id)
) ENGINE=MyISAM AUTO_INCREMENT=4 DEFAULT CHARSET=latin1
Here, we will get the sum of the price column from the table.
Query for sum():-
DB::table('product_info')->sum('price');
Query for sum() with where condition:-
DB::table('product_info')->where('quant…