how to calculate average in blade template?

岁酱吖の 提交于 2019-12-13 04:23:00

问题


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>&nbsp;{{$score->subject->subject_name}}</td>
<td>&nbsp;{{$score->result}}</td>
<td>&nbsp;{{$score->getGrade()}}</td>
<td>&nbsp;</td>
<td>&nbsp;</td>
<td>&nbsp;</td>
<td>&nbsp;</td>
<td>&nbsp;</td>
<td>&nbsp;</td>
<td>&nbsp;{{$score->final}}</td>
<td>&nbsp;{{$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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!