Using FontAwsome SVG and Laravel Blade to output a star rating


Simple code snippet to put out star outlines, stars and half stars as a rating

Uses Font Awesome (https://fontawesome.com/) for SVG icons

@foreach(range(1,5) as $i)
    <span class="fa-stack" style="width:1em">
        <i class="far fa-star fa-stack-1x"></i>

        @if($rating >0)
            @if($rating >0.5)
                <i class="fas fa-star fa-stack-1x"></i>
            @else
                <i class="fas fa-star-half fa-stack-1x"></i>
            @endif
        @endif
        @php $rating--; @endphp
    </span>
@endforeach

Note that $rating is expected to contain a value 0 to 5 (including fractions).  It will be affected by the $rating--; so keep a copy if you need it later.

By altering the stack order, the stars can be outlined.

 

Leave a comment

Your email address will not be published. Required fields are marked *