2014-06-14 92 views
4

我正在學習Laravel 4,迄今爲止都非常棒。但是對於一些奇怪的原因,刀片式的@foreach似乎不適用於簡單的查詢。我的代碼是:Laravel Blade @foreach not working

路線:

Route::get('/users', function(){ 

    $users = User::all(); 

    return View::make('users/index')->with('users',$users); 

}); 

現在index.blade.php我的代碼是:

@foreach ($users as $user) 

     <p>User: {{ $user->username }}</p> 

    @endforeach 

奇怪的是,當我傾倒的對象來看,它確實有效:

{{ dd($users->toArray())}} 

DB數據以數組形式顯示爲raw。

我不確定我在這裏做錯了什麼,這是初學者教程中的很多代碼。

+0

你用foreach循環得到的錯誤/問題是什麼? – Laurence

+0

沒有顯示任何內容,也沒有錯誤記錄。 –

+0

確保你使用'index.blade.php'作爲'view'文件的名字,我懷疑你錯過了'blade'。 –

回答

6

您應該使用template/layout(但你沒有按照你的view on Github使用)和子視圖應該擴大它,例如,您index.blade.php觀點應該是這個樣子:

// index.blade.php 
@extends('layouts.master') 
@section('content') 
    @foreach ($users as $user) 
     <p>User: {{ $user->username }}</p> 
    @endforeach 
@stop 

現在做肯定的是,在你的文件夾app/views/layouts你有master.blade.php佈局,它包含了這樣的事情:

// master.blade.php 
<!doctype html> 
<html class="no-js" lang=""> 
    <head> 
     <style></style> 
    </head> 
    <body> 
     <div class='content'> 
      @yield('content') {{-- This will show the rendered view data --}} 
     </div> 
    </body> 
</html> 

而且dd($users->toArray())的作品,因爲它轉儲$user->toArray()使用var_dump並使用die函數退出腳本,dd表示dump and die

+0

這工作得很好!非常感謝! –

+0

很高興它是有幫助的,歡迎你:-) –

+1

是的它有點令人困惑的教程沒有提到大師的意見,框架似乎真棒你。 –