Grace
Grace

Reputation: 299

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

Upvotes: 1

Views: 2562

Answers (3)

Chezz Ojeda
Chezz Ojeda

Reputation: 66

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.

Upvotes: 3

Imran
Imran

Reputation: 4750

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.

Upvotes: 4

user2094178
user2094178

Reputation: 9454

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

Upvotes: 1

Related Questions