一个不同的 "Invalid argument supplied for foreach()" 问题

A different "Invalid argument supplied for foreach()" issue

好的...所以...我搜索了 SO 和 Google 这个错误,但我找到的所有答案都与我的奇怪情况无关。

我刚刚安装了我的第一个 Laravel 5.3 应用程序(与之前的 5.2 一起使用)用作本地购物 list/price 检查应用程序。

正在尝试制作表格:

产品控制器:

$stores = Store::get();
return view('product.add', [
    'stores' => $stores,
]);

add.blade:

<select name="store_id" id="store_id">
@foreach ($stores as $store)
    <option value="{{ $store->id }}">{{ $store->name }} - {{ $store->address }}</option>
@endforeach
</select>

这会导致以下错误:

ErrorException in FormBuilder.php line 561:
Invalid argument supplied for foreach() (View: E:\wamp\www\shopping\resources\views\product\add.blade.php)

$stores 不为空,因为 dd($stores) 生成了一个包含我数据库中所有商店的集合。

我将此代码和 dd 结果与我的其他应用程序进行了比较,它们按预期工作,完全相同。我什至试过 @forelse.

Laravel 5.3 中是否有任何可能影响此的更改?我错过了什么吗?

一切看起来都很好。我认为有一个空数组 Array()

您必须在循环之前添加 if 条件,即

@if(!empty($stores))
@foreach ($stores as $store)
   <option value="{{ $store->id }}">{{ $store->name }} - {{ $store->address }}     </option>
@endforeach
@endif

由于@bagus-tesa 的评论,找到了问题所在。

错误消息中提到的 Formbuilder.php 是 LaravelCollective Form & HTML ("We maintain Laravel components that have been removed from the core framework"),这让我去查看该文件的第 561 行。有一个 foreach 语句,用于构建 select 输入。这让我意识到我的表单中还有另一个 select 列表,所以我查看了它。

{!! Form::select('category_id', null, null, array('class' => 'form-control')) !!}

第二个参数应该包含列表的选项数组,由 Formbuilder 使用 foreach 循环处理!

所以...我只是花了几个小时查看错误的 foreach 循环!