我试图建立一个小部件设计系统,用户可以提交小部件的标题和html。现在,当我尝试在视图中查询小部件模型并将数据传递给@foreach
循环时,我得到错误,因为@foreach
无法迭代Widget::all()
返回的查询集。我如何才能在我的网页上显示来自小部件模型的所有数据?
顺便说一句,我的Widget模型只有两个字段(i。E title and html).
编辑:以下是我做Widget::all()
时得到的回报的var_dump
array(2) { [0]=> object(Widget)#42 (5) { ["attributes"]=> array(3) { ["id"]=> string(1) "1" ["title"]=> string(24) "Join Demo classes today!" ["html"]=> string(47) "
This is just the great demo of widgets.
" } ["original"]=> array(3) { ["id"]=> string(1) "1" ["title"]=> string(24) "Join Demo classes today!" ["html"]=> string(47) "
This is just the great demo of widgets.
" } ["relationships"]=> array(0) { } ["exists"]=> bool(true) ["includes"]=> array(0) { } } [1]=> object(Widget)#45 (5) { ["attributes"]=> array(3) { ["id"]=> string(1) "2" ["title"]=> string(12) "About Google" ["html"]=> string(66) "Google is the best site in the world." } ["original"]=> array(3) { ["id"]=> string(1) "2" ["title"]=> string(12) "About Google" ["html"]=> string(66) "Google is the best site in the world." } ["relationships"]=> array(0) { } ["exists"]=> bool(true) ["includes"]=> array(0) { } } }
没有任何代码很难解决您的问题。下面是我要做的:
控制器:
$widgets = Widget::all();
View::make('html.widgets')->with('widgets', $widgets);
视图(叶片):
@foreach($widgets as $widget)
{{ $widget->title }}
{{ $widget->html }}
@endforeach
在您提到的问题中,查询视图中的小部件。由于这显然违反了MVC原则,但展示了laravel的灵活性,因此我还将向您提供一个片段,说明如何在没有控制器的情况下实现这一点。我建议而不是这样做:
@foreach(Widget::all() as $widget)
{{ $widget->title }}
{{ $widget->html }}
@endforeach