Home > Software engineering >  Laravel not passing 0 (zero) value in if else condition but pass null value
Laravel not passing 0 (zero) value in if else condition but pass null value

Time:08-07

laravel not passing 0 in else condition i have this code.

@foreach ($indicators as $indicator)
  @php
    if (!empty($indicator->rating)) {
      $rating = json_decode($indicator->rating, true);
      $starsum = array_sum($rating);
      $overallrating = $starsum/count($rating);
    }
    else{
      $overallrating = 0;
    }
  @endphp
@endforeach

CodePudding user response:

if $indicator->rating express a relationship you can replace

if (!empty($indicator->rating))

with this code it is searching if the relation exists

if($indicator->rating()->exists())

or count the items

if($indicator->rating->count() > 0)

if it is a json field in the $indicator you can first convert it to array and then check if not empty

$data = json_decode($indicator->rating, true);
if (!empty($data))
  • Related