2013-04-28 53 views
0

我試圖建立一個小部件設計系統,用戶可以提交小部件的標題和html.Now當我嘗試在視圖中查詢Widget模型並將數據傳遞到@foreach循環時,我得到的錯誤爲@foreach無法遍歷由Widget::all()返回的查詢集。如何在我的網頁上顯示來自Widget模型的所有數據?如何從Laravel的視圖中檢索所有模型數據?

Btw我的Widget模型只有兩個字段(即標題和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) { } } } 
+0

你是如何循環,它看起來像一個對象數組。必須是循環問題。 – 2013-04-28 09:04:21

+0

也許你可以展示你的行動代碼和你的視圖代碼。沒有理由不能迭代Widget :: all()的結果 – 2013-04-28 09:09:50

回答

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 
相關問題