如何从 Laravel 的视图中检索所有模型数据?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16261183/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to retrieve all model data from a view in Laravel?
提问by Rajat Saxena
I'm trying to build a widget designing system where a user can submit the title and html of the widget.Now when I try query the Widget model in a view and pass the data to @foreach
loop,I get the error as @foreach
is not able to iterate over the queryset returned by Widget::all()
.How can I display all the data from Widget model on my webpage?
我正在尝试构建一个小部件设计系统,用户可以在其中提交小部件的标题和 html。现在,当我尝试在视图中查询小部件模型并将数据传递给@foreach
循环时,我收到错误,因为@foreach
无法迭代返回的查询集。Widget::all()
如何在我的网页上显示来自 Widget 模型的所有数据?
Btw my Widget model has only two fields(i.e title and html).
顺便说一句,我的 Widget 模型只有两个字段(即标题和 html)。
EDIT:Following is the var_dump
of what I get in return when I do Widget::all()
编辑:以下是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) { } } }
回答by aebersold
It's hard to solve your problem without any code. Here's what I would do:
没有任何代码很难解决您的问题。这是我会做的:
controller:
控制器:
$widgets = Widget::all();
View::make('html.widgets')->with('widgets', $widgets);
view (blade):
视图(刀片):
@foreach($widgets as $widget)
{{ $widget->title }}
{{ $widget->html }}
@endforeach
In the question you're mentioning query the widget in a view. As this is clearly against MVC principles but demonstrates the flexibility of laravel, I will also give you a snippet how one can do that without a controller. I do notrecommend this:
在您提到的问题中,在视图中查询小部件。由于这显然违反了 MVC 原则,但展示了 laravel 的灵活性,我还将给你一个片段,如何在没有控制器的情况下做到这一点。我不建议这样做:
@foreach(Widget::all() as $widget)
{{ $widget->title }}
{{ $widget->html }}
@endforeach