Php Laravel检查集合是否为空
我的Laravel网络应用程序中有:Php Laravel检查集合是否为空,php,laravel,laravel-5.2,Php,Laravel,Laravel 5.2,我的Laravel网络应用程序中有: @foreach($mentors as $mentor) @foreach($mentor->intern as $intern) <tr class="table-row-link" data-href="/werknemer/{!! $intern->employee->EmployeeId !!}"> <td>{{ $intern->employee-&g
@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
它不会对此进行检查。要确定是否有任何结果,您可以执行以下任一操作:
if ($mentor->first()) { }
if (!$mentor->isEmpty()) { }
if ($mentor->count()) { }
if (count($mentor)) { }
if ($mentor->isNotEmpty()) { }
注释/参考资料
->first()
isEmpty()
->count()
count($mentors)
之所以有效,是因为集合实现了Countable和内部count()方法:
isNotEmpty()
因此,您可以做的是:
if (!$mentors->intern->employee->isEmpty()) { }
你可以随时数一数收藏。例如,
$mentor->intern->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
foreach($mentors作为$mentor)
@如果($mentor->intern->count()>0)
@foreach($mentor->intern作为$intern)
{{$intern->employee->FirstName}
{{$intern->employee->LastName}
@endforeach
@否则
导师没有实习生
@恩迪夫
@endforeach
这是最快的方法:
if ($coll->isEmpty()) {...}
其他解决方案,如count
所做的工作比您需要的要多一些,花费的时间稍微多一些
另外,
isEmpty()
名称非常精确地描述了您要在那里检查的内容,因此您的代码将更具可读性 从Laravel 5.3开始,您可以简单地使用:
if ($mentor->isNotEmpty()) {
//do something.
}
文档我更喜欢
(!$mentor)
从
php7
可以使用:
这将返回
Null
或员工。这是迄今为止我找到的最佳解决方案
刀片式
@if($mentors->count() == 0)
<td colspan="5" class="text-center">
Nothing Found
</td>
@endif
是的,我知道,但导师并不总是有实习生。那我怎么检查呢?`if($mentors->has('intern')){}我想如果$mentors->intern为空,就会出现一个错误。正确的方法如下:
$employee=$mentors->intern??空
为什么它更有效、更准确?
$employee = $mentors->intern ?? $mentors->intern->employee
@if($mentors->count() == 0)
<td colspan="5" class="text-center">
Nothing Found
</td>
@endif
if ($mentors->count() == 0) {
return "Nothing Found";
}