CakePHP 4 Sum column value
Asyraf Wahi Anuar - June 03, 2021Estimated reading time: 35 seconds

This tutorial is a very short one. How to sum the value from a column in a table? Let say you’ve table stocks [id, product, brand, quantity]. To sum the quantity value, you can apply the following code to your controller.
public function index()
{
$stocks = $this->paginate($this->Stocks);
//Count quantity
$total_quantity = $this->Stocks->find();
$count_quantity =$total_quantity->select(['sum' => $total_quantity->func()->sum('Stocks.quantity')])->first();
$sum_quantity = $count_quantity->sum;
$this->set(compact('stocks','sum_quantity'));
}
You can print the result using the following code in your view.
<?= $sum_quantity; ?>
That’s all. Happy coding :)
Cite this article (APA 6th Edition)
Popular

CakePHP 4 Print PDF Using CakePDF
May, 17 2020

CakePHP 4 Authentication Using Auth...
May, 14 2020

CakePHP 4 Sending Email
February, 01 2022

CakePHP 4 jQuery Date Time Picker
October, 01 2018

CakePHP 4 Export To CSV
May, 29 2020

CakePHP 4 Authentication Using...
May, 11 2020

CakePHP 4 Find, Sort & Count
June, 02 2020
Share