![](/img/trans.png)
[英]How to check in Laravel, if a table is completly empty, BEFORE do anything
[英]Laravel 8: How to check if table empty or not
我正在使用 Laravel 8 開發我的項目,在這個項目中,我有一個名為HomeController
的 Controller,他的這種方法是:
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 循環。 如果它為空,則不應顯示 table thead
標簽。
但現在的問題是它不起作用......我的意思是即使我在數據庫中沒有數據,它仍然會完全顯示thead
。
那么這段代碼有什么問題呢? 如何正確檢查表是否為空?
如果你能分享你的想法,我真的很感激......謝謝。
您正在返回收藏,它總是真正的compact('questions')
利用
if (!$questions->isEmpty()) # Laravel(in-built) way
if (!$questions->isEmpty())
// show data
else
echo "No record found.";
檢查這個條件
@if (isset($questions) && count($questions) > 0)
Inside Code
@endif
檢查附加條件為
&& count($questions) > 0
即使沒有收到數據,您也總是檢索一個雄辯的集合。 但是集合是可數的,所以你可以通過
if(count($collection))
如果 count 返回零,則該句子假定為 false
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.