Laravel 检查集合是否为空

Laravel check if collection is empty

我的 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))

它不检查那个。

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

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) 有效是因为 Collection 实现了 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()) { }

你总能数到collection。例如$mentor->intern->count()将return一位导师有多少实习生。

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

这是最快的方法:

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

其他解决方案,如 count 做的比您需要的要多一些,这会花费更多的时间。

此外,isEmpty() 名称非常准确地描述了您想在那里检查的内容,因此您的代码将更具可读性。

Laravel 5.3 开始,您可以简单地使用 :

if ($mentor->isNotEmpty()) {
//do something.
}

文档https://laravel.com/docs/5.5/collections#method-isnotempty

我比较喜欢

(!$mentor)

更有效和准确

php7 开始,您可以使用 Null Coalesce Opperator:

$employee = $mentors->intern ?? $mentors->intern->employee

这将 return Null 或员工。

这是迄今为止我找到的最佳解决方案。

在blade

@if($mentors->count() == 0)
    <td colspan="5" class="text-center">
        Nothing Found
    </td>
@endif

在控制器中

if ($mentors->count() == 0) {
    return "Nothing Found";
}

首先,您可以将集合转换为数组。接下来 运行 一个像这样的空方法:

if(empty($collect->toArray())){}