'Star and Half Star Rating in Laravel

I want to display average product ratings in star. The values are displaying good but I want to show half star if the value is in float.

My blade view:

<div class="rating">
  @for($i=0;$i<5;$i++)
    @if($product->ratings->avg('rating') > $i)
      <span class="icon-ratings"><i class="icon-rating icon-rating-x"></i></span>
    @else
      <span class="icon-ratings"><i class="icon-rating icon-rating-o"></i></span>
    @endif
  @endfor
 &nbsp; <div style="float:left">{{$product->ratings->avg('rating')}}</div>
</div>

The average value is showing 4.5. But all the 5 stars are filled with golden color. I want to fill half last star as that is a floating number.



Solution 1:[1]

use floor() function to detect float value like this

.................
@for($i=0;$i<5;$i++)

  <?php
    $thisRating = product->ratings->avg('rating')
    if(floor($thisRating) != $thisRating) {
      $hasHalfVal = 1;
    } else {
      $hasHalfVal = 0;
    }
  ?>

   @if($thisRating > $i && $hasHalfVal == 0)
     <span class="icon-ratings"><i class="icon-rating icon-rating-x"></i></span>
   @else if($thisRating > $i && $hasHalfVal == 1) 
     <span class="icon-ratings"><i class="icon-rating icon-rating-half"></i></span>
   @else
     <span class="icon-ratings"><i class="icon-rating icon-rating-o"></i></span>
   @endif

 .................

Solution 2:[2]

You can do that as below. For example in below answer I use font-awesome.

@for ($i = 1; $i <= 5; $i++)
    @if($product->ratings->avg('rating') < $i)
        @if (round($product->ratings->avg('rating')) == $i)


            <li class="list-inline-item me-0 small"><i
                    class="fas fa-star-half-alt text-warning"></i></li>
            @continue
        @endif
        <li class="list-inline-item me-0 small"><i
                class="far fa-star text-warning"></i></li>
        @continue
    @endif
    <li class="list-inline-item me-0 small"><i
            class="fas fa-star text-warning"></i></li>
@endfor

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 adam
Solution 2 Ali Sharifi Neyestani