Code The Pixel

CakePHP 4 Sum column value

Asyraf Wahi Anuar - June 03, 2021
Published in CakePHP 1362 Views Email This Article
Estimated 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)