【发布时间】:2021-05-30 16:42:34
【问题描述】:
我正在使用 Laravel 8 开发我的项目,在这个项目中,我有一个名为 HomeController 的控制器,他的这个方法是:
public function index()
{
$questions = Question::latest()->limit(5)->get();
return view('home', compact('questions'));
}
然后我在刀片上得到这样的结果:
@php
if ($questions)
{
@endphp
<table class="table table-striped table-bordered table-responsive BKoodakBold">
<thead class="thead-light">
<tr>
<th scope="col" class="forum-col" style="text-align:right;">Question</th>
<th scope="col" style="text-align:right;">Answer</th>
<th scope="col" style="text-align:right;">Rate</th>
<th scope="col" style="text-align:right;">Views</th>
</tr>
</thead>
<tbody>
@foreach($questions as $question)
<tr>
<td style="text-align:right;">
<h3 class="h5 mb-0"><a href="#0" class="text-uppercase">{{ $question->title }}</a></h3>
</td>
</tr>
@endforeach
</tbody>
</table>
@php
}
@endphp
如您所见,我设置if ($questions) 来检查此变量是否不为空,接下来执行for each 循环。如果为空,则不应显示表格thead 标签。
但现在的问题是它没有解决...我的意思是即使我在数据库中没有数据,它仍然完全显示表thead 。
那么这段代码有什么问题呢?如何正确检查表是否为空?
如果你能分享你的想法,我真的很感激......谢谢。
【问题讨论】:
-
你有一个 Collection,它是一个在 PHP 中总是真实的
true的对象 -
@lagbox 那么我现在该怎么做呢?
-
@if (isset($questions) && !empty($questions) && count($questions) > 0)@endif