Reputation: 8726
How can I find out the sum of certain columns of a row in MySQL using Laravel?
I know ->sum('something');
gives you the sum of a column. But what about a row?
Is there any method to do so in Laravel?
Currently I'm adding each column values manually and getting the sum.
Upvotes: 1
Views: 3064
Reputation: 595
How about this
return \DB::table('table_name')->sum('column_to_be_calculated');
Works for laravel 5 .
Upvotes: 0
Reputation: 152860
There is no built-in way to do this, but you can write a function yourself. Well, actually, I did that already for you! ;)
You have two options. The boring one, a function that just returns a predefined sum:
public function getSum(){
return $this->value1 + $this->value2; // and so on
}
Or a generic function that you can place inside a BaseModel
and use in every class and with every attributes you want:
public function getAttributeSum(){
$sum = 0;
foreach(func_get_args() as $attribute){
$sum += $this->getAttribute($attribute);
}
return $sum;
}
And you call it like this:
$model->getAttributeSum('value1', 'value2');
Upvotes: 2
Reputation:
Just create a model function and pass all the variables to it and do the calculation there. Then return the total and print wherever you want it.
{{Classmodel::total($yourvariablearray)}}
In the Classmodel.php
you will have something like:
public static function total($variablearray){
return $total = $variablearray->columnone + $variablearray->columntwo;
}
This should work.
Upvotes: 1