如何从数据库中获取数据到laravel中的查看页面?

Yos*_*tak 4 php mysql fetch laravel laravel-5.4

我正在使用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>
Run Code Online (Sandbox Code Playgroud)

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]);

});
Run Code Online (Sandbox Code Playgroud)

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

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

Yos*_*tak 7

[解决]

谢谢你们,我已经解决了这个问题

这是已解决的代码

web.php(路线)

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

    $petani = DB::table('tbl_user')->get();

    return view('listpetani', ['petani' => $petani]);
});
Run Code Online (Sandbox Code Playgroud)

在我的 listpetani.blade.php

@foreach($petani as $key => $data)
    <tr>    
      <th>{{$data->id_user}}</th>
      <th>{{$data->nama_user}}</th>
      <th>{{$data->alamat}}</th>
      <th>{{$data->no_telp}}</th>
      <th>{{$data->id_lokasi}}</th>                 
    </tr>
@endforeach
Run Code Online (Sandbox Code Playgroud)


Hem*_*mar 5

您也可以从视图中的数据库获取数据

@php( $contacts = \App\Contact::all() )  
@php( $owners = \App\User::all())  

<select class="form-control" name="owner_name" id="owner_name">                           
    @foreach($contacts as $contact)
      <option value="{{ $contact->contact_owner_id }}">{{ $contact->contact_owner }}</option>
    @endforeach                            
</select>  
Run Code Online (Sandbox Code Playgroud)

如果将数据从控制器传递到视图会更好。

return view('greetings', ['name' => 'Victoria']);
Run Code Online (Sandbox Code Playgroud)

查看文档: https://laravel.com/docs/8.x/views#passing-data-to-views


May*_*eyz 0

尝试这个:

$petani = DB::table('tbl_user')->pluck('id_user', 'username', 'alamat', 'no_telp', 'id_lokasi');
return view('listpetani', ['petani' => $petani]);
Run Code Online (Sandbox Code Playgroud)

在你的视图中$petani使用foreach()如下迭代:

foreach($petani as $data)
{
    echo $data->id_user;  // $petani is a Std Class Object here
    echo $data->username;
}
Run Code Online (Sandbox Code Playgroud)