Drennos
Drennos

Reputation: 313

Laravel: if foreach is empty

I have the next form in my aplication

  <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>

This brings all the devices associated with a specific user with if condition: $device->user_id == $user->id

But, there are users without associated devices. Then, the form should not show anything.

How to create a condition and an action when the user does not have associated devices

Upvotes: 1

Views: 3549

Answers (1)

Aken Roberts
Aken Roberts

Reputation: 13447

Blade comes with a directive to do exactly this.

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

Upvotes: 9

Related Questions