我正在尝试将一组行从控制器传递到视图:
$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
视图只会返回1个项目。 $ items的长度为1.如果我在控制器中count($items)
,我会得到预期的项目数。
如何从控制器将对象传递给我的视图?
控制器
$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
答案 0 :(得分:2)
问题是在致电exists()
之前致电get()
。对exists()
的调用正在修改您的查询构建器,以便向其添加limit(1)
。因此,当您在get()
之后致电exists()
时,查询构建器仍会附加limit(1)
。
您的更新解决方案有效,因为您删除了对exists()
的调用。
但是,get()
的调用仍应在Controller中完成。视图应仅传递给对象集合,而不是查询构建器。
答案 1 :(得分:0)
我相信如果你把get()放在最后它会起作用。
$items = Items::where('group', '=', $group)->get();
您只是拉回模型对象而不是数据。这就是为什么当你期待4时计数是1。
根据评论编辑
我觉得你拥有它的地方可能会造成一些困难。
$items = Items::where('group', '=', $group)->get();
return view('listing', [
"group" => $group,
"items" => $items,
]);
@if (!$items->exists())
Nothing
@else
<ul id="items">
@foreach ($items as $item)
<li>
{{ $item->user }}: {{ $item->content }}
</li>
@endforeach
</ul>
@endif
在查询项目后,您可以放置dd($items->toArray());
以查看所获得的内容。