如何从Laravel中的视图中检索所有模型数据?

时间:2013-04-28 08:46:43

标签: php laravel

我正在尝试构建一个小部件设计系统,用户可以在其中提交小部件的标题和html。现在,当我尝试在视图中查询Widget模型并将数据传递给@foreach循环时,我得到错误,因为@foreach无法迭代Widget::all()返回的查询集。如何在我的网页上显示Widget模型中的所有数据?

顺便说一句,我的Widget模型只有两个字段(即title和html)。

编辑:以下是我var_dump时获得的Widget::all()

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) { } } }

1 个答案:

答案 0 :(得分:2)

没有任何代码,很难解决您的问题。这就是我要做的事情:

控制器:

$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