Laravel:如果foreach为空

时间:2018-08-11 18:24:35

标签: php laravel if-statement foreach

我的应用程序中有下一个表格

  <div class="form-group">
  <ul class="list-unstyled">
    <table class="table">
      <thead>
        <tr>
          <td>User ID</td>
          <td>Responsable</td>
          <td>Equipo</td>
          <td>Revision fisica</td>
          <td>Observación</td>
          <td>Revision lógica</td>
          <td>Observación</td>
        </tr>
      </thead>
      <tbody>
        @foreach($devices as $device)
        <tr>
          @if($device->user_id == $user->id and $device->status == 'active')
          <td>
            <input type="text" readonly="readonly" name="user_id[]" value="{{auth()->user()->id}}" class="form-control" >
          </td>
          <td>
            <input type="text" readonly="readonly" name="responsable[]" value="{{$device->user->name}}" class="form-control" >
          </td>
          <td>
            <input type="text" readonly="readonly" name="device_name[]" value="{{$device->name}}" class="form-control">
          </td>
          <td>
            <select name="physical_review[]" class="form-control">
              <option value="OK">OK</option>
              <option value="NOK">NOK</option>
            </select>
          </td>
          <td>
            {{ Form::text('physical_overview[]', null, ['class' => 'form-control', 'id' => 'physical_overview']) }}
          </td>
          <td>
            <select name="logical_review[]" class="form-control">
              <option value="OK">OK</option>
              <option value="NOK">NOK</option>
            </select>
          </td>
          <td>
            {{ Form::text('logical_overview[]', null, ['class' => 'form-control', 'id' => 'logical_overview']) }}
          </td>
          @endif
        </tr>
        @endforeach
      </tbody>
    </table>

    </ul>
</div>
<div class="form-group">
  {{ Form::submit('Guardar', ['data-confirm' => 'Are you sure you want to delete?']) }}
</div>

这会使所有与特定用户关联的设备具有if条件:$ device-> user_id == $ user-> id

但是,有些用户没有关联的设备。然后,该表格不应显示任何内容。

当用户没有关联的设备时如何创建条件和动作

1 个答案:

答案 0 :(得分:6)

Blade comes with a directive to do exactly this.

@forelse ($devices as $device)
    <tr>
         ...
    </tr>
@empty
    <p>This user has no devices.</p>
@endforelse