【问题标题】:Laravel 8: How to check if table empty or notLaravel 8:如何检查表是否为空
【发布时间】: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

标签: php laravel laravel-8


【解决方案1】:

你正在返回收藏,这是真的compact('questions')

使用

if (!$questions->isEmpty())  # Laravel(in-built) way

if (!$questions->isEmpty())
  // show data
else
  echo "No record found.";

【讨论】:

  • 您不能为此使用empty
  • @lagbox 谢谢,isEmpty 将使用集合。
  • @lagbox 好的。注意到
【解决方案2】:

检查这个条件

    @if (isset($questions) && count($questions) > 0)

       Inside Code

    @endif

【讨论】:

  • 您不能为此使用empty
  • @lagbox 好的。谢谢
【解决方案3】:

检查附加条件为

&& count($questions) > 0

【讨论】:

    【解决方案4】:

    即使没有收到任何数据,您也总是会检索一个雄辩的集合。但是collection是可数的,所以你可以通过

    if(count($collection))
    

    如果计数返回零,则句子假设为假

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-05-07
      • 2019-06-09
      • 1970-01-01
      • 2013-12-23
      • 2020-02-04
      • 2023-03-28
      • 2022-01-09
      • 1970-01-01
      相关资源
      最近更新 更多