Home > database >  I Don't Know Why My If Statement Didn't Work (Laravel)
I Don't Know Why My If Statement Didn't Work (Laravel)

Time:01-02

I have problem with my if statement, I try to display star base on average rating, for example if average 4.8 then should display warning star 4, but I have trying make statement only read first statement, the following is my condition code:

@if($reviews->average('rating') >= '3')
@for($i=1;$i<4;$i  )
    @php echo $i ? "<i class='mdi mdi-star me-n1 text-warning'></i>" : "<i class='mdi mdi-star me-n1 text-light'></i>"; @endphp
@endfor
@elseif($reviews->average('rating') >= '4')
@for($i=1;$i<5;$i  )
    @php echo $i ? "<i class='mdi mdi-star me-n1 text-warning'></i>" : "<i class='mdi mdi-star me-n1 text-light'></i>"; @endphp
@endfor
@endif

Please help me why my second statement didn't read, In this case the second statement should be read. Who anyone can help much appreciate.

CodePudding user response:

As explained in the comments the problem lays in the else if logic. You can use the review average directly in your for-loop if you adjust the comperator to <= instead of <. This makes the if statements somewhat obsolete.

@for($i=1;$i <= $reviews->average('rating');$i  )
    @php echo $i ? "<i class='mdi mdi-star me-n1 text-warning'></i>" : "<i  class='mdi mdi-star me-n1 text-light'></i>"; @endphp
@endfor

In case the average is for example 4.5, the loop is going to execute 4 times. In case it is 3 it executes 3 times. In case of 3.5 it executes also 3 times. You might need to add a functionality for partial stars or for rounding the number. Otherwise the displayed star rating and the actual rating might differ too much. For example, an average of 3.9 would be displayed as 3 but it would be more intuitiv to display 4 stars.

  • Related