如何从数据库中获取数据以在 laravel 中查看页面?

新手上路,请多包涵

我正在使用 Laravel 5.4,我想从我的视图页面( listpetani.blade.php )查看我在数据库中的数据。

这是我的项目的代码:

HTML:

 <div class="table-responsive">
  <table class="table table-striped table-hover table-condensed">
    <thead>
      <tr>
        <th><strong>No</strong></th>
        <th><strong>Nama Petani</strong></th>
        <th><strong>Alamat</strong></th>
        <th><strong>No. Handphone</strong></th>
        <th><strong>Lokasi</strong></th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <th></th>
        <th></th>
        <th></th>
        <th></th>
        <th></th>
      </tr>
    </tbody>
  </table>
</div>

PHP:在我的 listpetani.blade.php 我有一个空表,我想显示来自 数据库 tbl_user 的数据:

 Route::get('listpetani', function () {

  $petani = DB::table('tbl_user')->pluck('id_user', 'username', 'alamat', 'no_telp', 'id_lokasi');

  return view('listpetani', ['petani' => $petani]);

});

还有我页面中的表格: 在浏览器 中查看

我想在 laravel 5.4 中将数据库中的所有数据显示到我的视图中。有谁能够帮我?

原文由 Yosua Michael 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 490
1 个回答

我希望您已经知道这一点,但也可以尝试使用 Model 和 Controller,让路由接受请求,并将其传递给控制器并使用 Eloquent,这样您的代码就可以这么短:

 $petani = PetaniModel::all();
return view('listpetani', compact('petani));

and instead using foreach , use forelse with @empty statement incase your 'listpetani' is empty and give some information to the view like ‘The List是空的’。

原文由 Egy2015 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题