繁体   English   中英

Laravel 8:如何检查表是否为空

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM