【问题标题】:Blade: Invalid argument supplied for foreach()Blade:为 foreach() 提供的参数无效
【发布时间】:2020-09-14 11:15:42
【问题描述】:

有时 $structures 数组有空值,其他变量的相同代码工作正常,但在这种情况下不是。

@foreach($structures ?? [] as $item) {{ $item }} @endforeach

【问题讨论】:

  • 我不认为 foreach 是这样工作的。在 foreach 之前添加一个 if。

标签: php laravel laravel-blade php-7


【解决方案1】:

我通过在 $structures ?? [] 表达式周围添加 () 解决了这个问题。

@foreach(($structures ?? []) as $item) {{ $item }} @endforeach

【讨论】:

  • 如果$structures 的值为空,我只需要一个空数组。
【解决方案2】:

使用forelse 而不是foreach

@forelse ($structures as $item)
{{ $item }}
@empty 
No Items found.
@endforelse

forelse检查条件如下。

@if ($structures->count())
  @foreach ($structures as $item)  
 {{ $item }}
  @endforeach
@else
No Items found.
@endif

【讨论】:

  • 这很有用,但我不想在我的代码中清空条件,在这种情况下,空@empty 条件看起来很糟糕。
  • 即使@forelse 也会出现同样的错误。为 ... 提供的参数无效
猜你喜欢
  • 2018-02-26
  • 2011-05-17
  • 2011-02-07
相关资源
最近更新 更多