问题
with this image
Is it possible to calculate the average inside blade template? I'm using foreach loop to show the subject and grade of the student and on the average section how can I total average, what is the best approach on this matter calculate through blade or controller? aim is to generate total avarage.
here is the view code:
@foreach($scores as $score)
<td> {{$score->subject->subject_name}}</td>
<td> {{$score->result}}</td>
<td> {{$score->getGrade()}}</td>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
<td> {{$score->final}}</td>
<td> {{$score->average()}}</td>
@endforeach
回答1:
The best way to avoid confusion is to calculate the average in the controller and send it as a variable, so you don't have to manipulate data in the view. You can do it both ways, manually in the view or using the model in the controller.
Here is an example of using the model: How to get average of column values in laravel
$average = Scores::avg('average')
Or do it in the view manually by adding previous values to a variable and dividing with count($scores).
Hope it helps.
回答2:
You can achieve a total average by using $scores->avg('average')
.
回答3:
So, it's seems your $score is a collection instance. You can use any method available in Laravel collection: https://laravel.com/docs/5.6/collections#available-methods
If you check this link carefully there is a method called avg()
. Using this method you can calculate the average of any given key. In blade:
{{round($scores->avg('average'), 2)}}
Here, $scores->avg('average')
will calculate the average of all average
value of scores and round()
function will round it up to 2 decimal point.
来源:https://stackoverflow.com/questions/51604059/how-to-calculate-average-in-blade-template