mchomvu
mchomvu

Reputation: 717

How to count column

I have twelve integer input field of students marks, a student can attempt to a maximum of 10 exam and minimum of 7 exam, my problem is when a student attempt 7 exam i need its average to be of 7 subject only, Who can help me to perform this.

I did my calculation in view

    <td>{{round(((
           $formone->civ +
           $formone->hist +
           $formone->geo +
           $formone->kisw +
           $formone->engl +
           $formone->phy +
           $formone->chem +
           $formone->bio +
           $formone->ict +
           $formone->bm +
           $formone->comm +
           $formone->bk
         )/12),3)}} 
    </td>
    <td>{{ $formone->civ +
           $formone->hist +
           $formone->geo +
           $formone->kisw +
           $formone->engl +
           $formone->phy +
           $formone->chem +
           $formone->bio +
           $formone->ict +
           $formone->bm +
           $formone->comm +
           $formone->bk
        }} 
    </td>

Upvotes: 0

Views: 63

Answers (1)

Yash Malla
Yash Malla

Reputation: 366

You can have a accessor on the model to calculate the average.

/* ACCESSORS */
public function getAverageAttribute()
{
    $subjects = ['civ', 'hist', 'geo', 'kisw', 'engl', 'phy', 'chem', 'bio', 'ict', 'bm', 'comm', 'bk',];
    $subjectCount = 0;
    $totalMarks = 0;

    foreach ($subjects as $subject) {
        // ASSUMPTION: Marks are null if the student did not attempt it.
        if ($this->attributes[$subject]) {
            $totalMarks += $this->attributes[$subject];
            $subjectCount++;
        }
    }
    return round($totalMarks / $subjectCount, 3);
}

And use it your view like

<td> {{$formone->average}} </td>

Upvotes: 1

Related Questions