我正在尝试将一组行从 Controller 传递到 View :
$items = Items::where('group', '=', $group);
return view('listing', [
"group" => $group,
"exists" => $items->exists(),
"items" => $items->get(),
]);
在我看来:
@if (!$exists)
Nothing
@else
<ul id="items">
@foreach ($items as $item)
<li>
{{ $item->user }}: {{ $item->content }}
</li>
@endforeach
</ul>
@endif
该 View 仅返回 1 项。 $items 的长度为 1。如果我在 Controller 中 count($items)
,我会得到预期的项目数。
如何将对象从 Controller 传递到我的 View ?
我的最终解决方案:
Controller
$items = Items::where('group', '=', $group);
return view('listing', [
"group" => $group,
"items" => $items->get(),
"exists" => $items->exists(), // Important! Has to go after!
]);
在我看来:
@if (!$exists)
Nothing
@else
<ul id="items">
@foreach ($items as $item)
<li>
{{ $item->user }}: {{ $item->content }}
</li>
@endforeach
</ul>
@endif
最佳答案
问题是在调用 get()
之前调用了 exists()
。对 exists()
的调用正在修改您的查询构建器以向其添加 limit(1)
。因此,当您在 exists()
之后调用 get()
时,查询构建器仍然附加了 limit(1)
。
您更新的解决方案有效,因为您删除了对 exists()
的调用。
但是,对 get()
的调用仍应在 Controller 中完成。 View 只能传递对象集合,而不是查询生成器。
关于php - 将对象从 Controller 传递到 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30577232/