【问题标题】:How to not show empty collection如何不显示空集合
【发布时间】:2021-09-29 11:53:19
【问题描述】:

我已尝试将此代码添加到我的 Blade:

@if(!empty($user_wallet))
    <li class="mt-3" id="theWallet">
        <div class="form-check">
            <input class="form-check-input" type="checkbox" name="pay_wallet" value="1" id="thisWrapper">
            <label class="form-check-label small mr-3" for="thisWrapper">
            Pay with Wallet
            </label>
        </div>
    </li>
@endif

所以这意味着,如果用户没有任何 Wallet,则不要显示 id 为 theWallet 的 div。

但现在的问题是,它仍然显示 div 和复选框,但是用户没有任何钱包存储在数据库中。

当我dd($user_wallet) 时,我得到了这个:

Illuminate\Database\Eloquent\Collection {#2562 ▼
  #items: []
}

也就是说,它是空的。但是为什么它仍然显示 div?

【问题讨论】:

  • 试试if(!$user_wallet-&gt;isEmpty())收集方法
  • empty(): Determine whether a variable is considered to be empty. A variable is considered empty if it does not exist or if its value equals false. empty() does not generate a warning if the variable does not exist. 并且你有一个数组,即使数组为空,变量本身也不是,
  • 这能回答你的问题吗? Laravel check if collection is empty

标签: php laravel laravel-5.8


【解决方案1】:

isset() 函数与empty() 函数结合使用。

将 if 条件替换为

@if(!empty($user_wallet))

@if(!empty($user_wallet) && isset($user_wallet)) 

or 

@if(isset($user_wallet))

isset() 函数是 PHP 中的一个内置函数,用于检查变量是否已设置且不为 NULL。

此函数还检查声明的变量、数组或数组键是否为空值,如果是,isset() 返回 false,在所有其他可能的情况下返回 true。

【讨论】:

  • 这是一个集合实例。它始终设置为传递给视图。这里需要检查的是,集合的空性。
【解决方案2】:

您好,如果 $user_wallet 包含集合数据,那么您需要更改 @if 条件。

更换你的

@if(!empty($user_wallet))

@if(!$user_wallet->isEmpty()) OR @if($user_wallet->isNotEmpty())

【讨论】:

    猜你喜欢
    • 2020-04-01
    • 1970-01-01
    • 2021-11-03
    • 1970-01-01
    • 2022-10-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多