但是,如果(!empty($tags))的计算结果为true,则集合为空



只有当$tags集合不为空时,我才会尝试呈现一些HTML代码。然而,即使集合是空的,HTML代码也会被呈现出来。

当我dd($tags)时,我得到一个空的[]。为什么会发生这种情况?

@if(!empty($tags))
<p><i class="fas fa-tags"></i> Tags</p>
<div class='image-tags'>
@foreach($tags as $tag)
<a class='image-tag' href="#">{{ $tag->name }}</a>
@endforeach
</div>
@endif

尝试

@if(count($tags) > 0)
More code here ....
@endif

因为$tags是阵列

PHP将Laravel集合视为一个对象。如果该对象不是null,则empty函数将始终返回true。如果要检查集合是否包含元素,可以使用isNotEmpty集合函数。

@if($tags->isNotEmpty())
@endif

如果是laravel集合,则应该将count($tags)用于类数组或$tags->count()

请检查此url,http://php.net/manual/en/function.empty.php这里给出了空函数的正确用法。

在你的条件下,如果$tags是一个数组,那么你应该这样使用:

if(count($tags) > 0)

最新更新