2017-05-08 101 views
0

我想在我的表單下的主頁上顯示我的帖子。 我已經可以將帖子添加到我的數據庫中。LARAVEL - 將變量從控制器傳遞到查看

現在我只是得到未定義的變量,如果我嘗試在我的查看頁面中使用此變量。

路線=

Route::resource('posts', 'PostController'); 

控制器=

public function show() 
{ 
    $posts = Post::orderBy('created_at', 'asc')->get(); 

    return view('/home', [ 
     'posts' => $posts 
    ]); 
} 

查看

@if (count($posts) > 0) 
    <div class="panel panel-default"> 
     <div class="panel-heading"> 
      Posts 
     </div> 

     <div class="panel-body"> 
      <table class="table table-striped task-table"> 

       <!-- Table Headings --> 
       <thead> 
       <th>Posts</th> 
       <th>&nbsp;</th> 
       </thead> 

       <!-- Table Body --> 
       <tbody> 
       @foreach ($posts as $post) 
        <tr> 
         <!-- Post Name --> 
         <td class="table-text"> 
          <div>{{ $post->description }}</div> 
         </td> 
        </tr> 
       @endforeach 
       </tbody> 
      </table> 
     </div> 
    </div> 
@endif 
+0

嘗試在控制器中打印$ posts以查看它顯示的內容。同樣在你的視圖中,在循環之前添加if條件if(isset($ posts))。並且,如果您需要更多幫助,請在此處發佈您的視圖代碼 – manian

+0

顯示您的視圖代碼以訪問該變量。 –

+0

你從哪裏得到一個錯誤?在網頁上?在日誌文件中? – PKeidel

回答

0

試試這個

public function show() 
{ 
    $posts = Post::orderBy('created_at', 'asc')->get(); 

    return view('home', [ 
     'posts' => $posts 
    ]); 
} 

並向我們展示您的刀片視圖,路徑和名稱?

+0

不,同樣的錯誤.. – Mette

+0

並向我們展示你的刀片視圖,什麼路徑和名字? – mikrafizik

+0

哈哈,不喜歡,這是真實的答案,你有一個問題與你的看法的名稱 – mikrafizik

0

,你可以嘗試使用:

返回查看( '/家',緊湊型(「帖));

這對我有用。

1

正確的方法是使用Route :: resources()僅適用於REST(只是我的意見)。嘗試創建一個新的路由像

Route::get('hello-there', [ 
    'as' => 'front.index', 
    'uses' => '[email protected]', 
]); 

現在ü可以得到通過訪問你的行動:「wwww.mydomain.com/hell-there 下一步 - 使命名行動‘索引’,如果它是名單

public function index() 
{ 
    return view('home', [ 
     'posts' => Post::orderBy('created_at', 'asc')->get(), 
    ]) 
} 

ü需要在以下目錄中名爲「home.blade.php」刀片視圖文件:

application_path/resources/

刀片文件看起來是正確的好運墊即

+0

感謝隊友,路線::資源()是我想先做的方式,但這工作得很好。 – Mette

相關問題