How to get data from database to view page in laravel?
Stefan Izdrail
Founder & Senior Architect · 2026-06-29
Title: Displaying Database Data in Laravel Views Effortlessly
Introduction
Laravel is a powerful PHP framework that offers various features to simplify web application development. One of these features includes retrieving data from your database and displaying it on the front-end page, also known as views. In this blog post, we will demonstrate how to retrieve data from a table in your Laravel 5.4 project and show it in the view file listpetani.blade.php.
Retrieving Data From Database
First, let's create an empty database table called tbl_user with columns: id_user (primary key), username, alamat, no_telp, and id_lokasi. Then, fill the table with some sample data as shown in the image above.
Since you want to display all the data from your table tbl_user in the listpetani view, we'll follow these steps:
1. In the web browser, navigate to http://localhost/listpetani, which should be the URL you've set up for this route. You should see an empty HTML table as per your code.
2. Return the data from the database in your route 'listpetani':
Route::get('listpetani', function () {
$petani = DB::table('tbl_user')->pluck('id_user', 'username', 'alamat', 'no_telp', 'id_lokasi');
return view('listpetani', ['petani' => $petani]);
});
3. In the listpetani.blade.php file, where your empty HTML table is, use a foreach loop to iterate through each row of data:
<table id="tblPetani" 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>
@foreach($petani as $k => $v)
<tr>
<td>{ $k + 1 }
<td>{ $v['username'] }
<td>{ $v['alamat'] }
<td>{ $v['no_telp'] }
<td>{ App\Models\Lokasi::find($v['id_lokasi'])->nama_lokasi }
</tr>
@endforeach
</tbody>
</table>
4. In the above code, first you added a table with appropriate class and header tags. Then used Laravel's built-in method pluck() to retrieve data from the database table tbl_user. The result is stored in an array which is then passed to the view as a variable called 'petani'.
5. In the loop, you iterate over each row of the data, generating rows for your HTML table that contain indexes (starting from 1), usernames, addresses, phone numbers and lokasi names. This will display all the users in your database on the listpetani page.
Conclusion
In this blog post, we have shown you how to easily retrieve data from a specific table in your Laravel project and display it on your view page. By following these steps, you'll be able to showcase relevant information from the database without any hassle. This method is scalable and can be expanded or adapted for various tables and views with just a few tweaks.