In this post, you will learn how to get a column sum in laravel eloquent. This is the common thing to do when you need to get the sum of column values.
By the end of this article, you will know how to get a sum of the column values in laravel eloquent.
Let’s get started.
Table of Contents
Syntax of getting sum in laravel eloquent
ModelName::sum('column_name');
Example:
Let’s say we have ProductOrdered
model in which we have:
- user_id
- product_name
- price
and we need to get the sum of all the products price user_id=1
ordered.
So the controller we will write:
$sum=ProductOrdered:where('user_id',1)->sum('price');
echo $sum;
This will return as the sum of all the product’s price which user_id=1
as ordered.
Conclusion:
Hope you have learned today how to get a sum of column values in laravel eloquent.
Let me know if you have any related questions.
See you soon again!
Write a Reply or Comment