无法在 blade 视图中检索数据库信息

Cannot retrieve database info in blade view

我无法将数据库信息传递到我的 blade 文件。我想在一页上显示所有数据库条目。我做错了什么?

diary.blade.php

 @foreach($posts as $post)
     <Tr>
         <th>{{ $post->id }}</th>
         <th>{{ $post->body }}</th>
     </Tr>
 @endforeach

web.php

Route::get('diary', 'DiaryController@index')->name('diary');

DiaryController.php

 public function index()
 {
     $posts = DB::table('entries')->get();
     return view ('user.diary')->with('diary', $posts);
 }

应该是

return view ('user.diary')->with('posts', $posts);

您传递的变量名称不正确,而不是

return view ('user.diary')->with('diary', $posts);

你应该做的

return view ('user.diary')->with('posts', $posts);

这里有一些可以将数据传递到视图的替代方法:-

return view('user.diary', ['posts' => $posts]);

return view ('user.diary')->with('posts', $posts);

return view('user.diary', compact('posts'));

希望这对您的问题有所帮助。