Подтвердить что ты не робот

Проверка Laravel, если коллекция пуста

У меня это есть в моем Laravel webapp:

@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

Как я могу проверить, есть ли $mentors->intern->employee?

Когда я делаю:

@if(count($mentors))

Он не проверяет это.

4b9b3361

Ответ 1

Вы всегда можете подсчитать коллекцию. Например, $mentor->intern->count() вернет, сколько стажеров имеет наставник.

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

В вашем коде вы можете сделать что-то вроде этого

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

Ответ 2

Чтобы определить, есть ли какие-либо результаты, вы можете выполнить одно из следующих действий:

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

Примечания/Ссылки

->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) работает, потому что Collection реализует счетный и внутренний метод count():

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

Итак, что вы можете сделать:

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

Ответ 4

Это самый быстрый способ:

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

Другие решения, такие как count делают немного больше, чем вам нужно, что стоит немного больше времени.

Кроме того, имя isEmpty() довольно точно описывает, что вы хотите проверить там, чтобы ваш код был более читаемым.

Ответ 5

я предпочитаю

(!$mentor)

Более эффективен и точен