2016-03-07 9 views
11

ho questa nel mio webapp laravel:controllo laravel se la raccolta è vuoto

@foreach($mentors as $mentor) 
    @foreach($mentor->intern as $intern) 
     <tr class="table-row-link" data-href="/werknemer/{!! $intern->employee->EmployeeId !!}"> 
      <td>{{ $intern->employee->FirstName }}</td> 
      <td>{{ $intern->employee->LastName }}</td> 
     </tr> 
    @endforeach 
@endforeach 

Come potrei controllare se ci sono eventuali $mentors->intern->employee?

Quando faccio:

@if(count($mentors)) 

Esso non verifica per questo.

risposta

8

Puoi sempre contare la collezione. Ad esempio $mentor->intern->count() restituirà quanti stagisti ha un mentore.

https://laravel.com/docs/5.2/collections#method-count

Nel codice si può fare qualcosa di simile

foreach($mentors as $mentor) 
    @if($mentor->intern->count() > 0) 
    @foreach($mentor->intern as $intern) 
     <tr class="table-row-link" data-href="/werknemer/{!! $intern->employee->EmployeeId !!}"> 
      <td>{{ $intern->employee->FirstName }}</td> 
      <td>{{ $intern->employee->LastName }}</td> 
     </tr> 
    @endforeach 
    @else 
     Mentor don't have any intern 
    @endif 
@endforeach 
21

per determinare se ci sono risultati che si possono fare le seguenti:

if ($mentor->first()) { } 
if (!$mentor->isEmpty()) { } 
if ($mentor->count()) { } 
if (count($mentor)) { } 

Note/Riferimenti

->first()

http://laravel.com/api/5.2/Illuminate/Database/Eloquent/Collection.html#method_first

isEmpty()http://laravel.com/api/5.2/Illuminate/Database/Eloquent/Collection.html#method_isEmpty

->count()

http://laravel.com/api/5.2/Illuminate/Database/Eloquent/Collection.html#method_count

count($mentors) opere perché il Collection utilizza Contabile e un metodo di conteggio interno():

http://laravel.com/api/5.2/Illuminate/Database/Eloquent/Collection.html#method_count

Che cosa si può fare è:

if (!$mentors->intern->employee->isEmpty()) { } 
+0

sì, lo so che, ma un mentore non lo fa sempre ha una stagista. Quindi come potrei controllarlo? – Jamie

4

Questo è il modo più veloce:

if ($coll->isEmpty()) {...} 

altre soluzioni come count fanno un po 'più del necessario, che costa un po 'più di tempo.

Inoltre, il nome isEmpty() descrive in modo abbastanza preciso ciò che si desidera controllare, in modo che il codice sia più leggibile.