Adding a Star Rating system to your application – Step 6 - Viewing an average of all ratings submitted

Laravel Eloquent provides a range useful functions that operate over Collections. Collections are basically a more sophisticated version of an array of object with a range of additional features which allow you to query, filter and control the results. Some useful functions can be found here One of these methods provides an ability to get the average of a particular field in the collection. We want to use this to get the average all ratings for a particular tennis court and display it on the courts page.

Similar functionality to this is to be found on every E-Commerce and Online Community website out there. As more and more people rate an individual product or service other online shoppers or community members get to avail of the "wisdom in the crowd".

To see the average rating, we need only modify the view associated with the courts index page so as to reflect the average rating of each court. Open the file /resources/views/courts/table.blade.php. First add in two new column headings for the average rating and the stars as follows

Next add two new columns in the table - the first displays the average ratings for all courts rounded to two decimal places. It does this by "walking the object tree" on the relationship between courts and courtratings. This returns a collection class of courtratings. From here we can call the avg( ) method on the collection class which will get an average of all the ratings for that given court.

<td>{!! round($court->courtratings->avg('rating'),2); !!}</td> 

The second "stars" column basically displays the same information but it is encased in an input tag with the star rating css class attached to ensure it will display as a set of stars.

<td><input id="fieldRating" name="rating" value="{!! round($court->courtratings->avg('rating'),2); !!}" type="text" class="rating rating-loading" data-min=0 data-max=5 data-step=1 data-size="sm" data-display-only="true"> </td>

This two table columns are placed alongside the other table columns in the database as follows

Now the courts index page http://localhost:8000/courts will appear as follows

In the next post we'll examine how to drill-down on the stars to see the detail behind the ratings.

Leave a Reply