how to calculate average in blade template?

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP

how to calculate average in blade template?



with this imageenter image description here



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


@endforeach




3 Answers
3



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.





thank you sir got it hehehe
– Grace
33 mins ago






You can use round() More info here: php.net/manual/es/function.round.php
– Chezz Ojeda
30 mins ago



You can achieve a total average by using $scores->avg('average').


$scores->avg('average')





blade will recognized, avg/? automatically
– Grace
50 mins ago





how to round the average
– Grace
45 mins ago



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:


avg()


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.


$scores->avg('average')


average


round()






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Comments

Popular posts from this blog

Executable numpy error

PySpark count values by condition

Mass disable jenkins jobs