Calculate vote percentages with the Collection class

Submitted by meigwilym - 9 years ago

You have election data in your database. Perhaps each candidate has 1 record, with his/her name and number of votes. The percentage of the vote that each candidate attained can be calculated per candidate, without having to loop through the data. Laravel's Collection class provides the `sum($column_name)` method, which sums the column totals. This can then be used to calculate the vote share. I've used PHP's `format_number` function to round up the final percentage. Extra points given for a bootstrap progress bar, to illustrate the vote share.

/*
Database table:

election_results
id | name | votes
1 | Steve | 245
2 | Lisa | 376
3 | John | 126
*/

$results = ElectionResults::all();

$total_votes = $results->sum('votes');

// View file
<table class="table table-striped">
  <thead>
    <tr>
      <th>Name</th>
      <th>Votes</th>
      <th>Percentage</th>
    </tr>
  </thead>
  <tbody>
    @foreach($results as $result)
    <tr>
      <td>{{{ $result->name }}}</td>
      <td>{{{ $result->votes }}}</td>
      <td>
        {{ format_number((($result->votes/$total_votes) * 100), 2) }}%
        <div class="progress" title="{{ $result->percent }}%">
          <div class="progress-bar progress-bar-info" style="width: {{ $result->percent }}%"></div>
        </div>  
      </td>
    </tr>
    @endforeach
  </tbody>
</table>