Laravel 检查集合是否为空

2022-08-30 08:05:58

我已经在我的Laravel网络应用程序中得到了这个:

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

它不会检查这一点。


答案 1

要确定是否有任何结果,您可以执行以下任一操作:

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

注释/参考文献

->first()

https://laravel.com/api/5.7/Illuminate/Database/Eloquent/Collection.html#method_first

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

->count()

https://laravel.com/api/5.7/Illuminate/Database/Eloquent/Collection.html#method_count

count($mentors)之所以有效,是因为集合实现了 Countable 和内部 count() 方法:

https://laravel.com/api/5.7/Illuminate/Database/Eloquent/Collection.html#method_count

isNotEmpty()

https://laravel.com/docs/5.7/collections#method-isnotempty

所以你可以做的是:

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

答案 2

您始终可以计算集合。例如,将返回导师有多少实习生。$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

推荐