Retrieve Records Query Builder Laravel 8

Bài này chúng ta sẽ học cách dùng Query Builder trong Laravel 8 để Retrieve Records (truy xuất bản ghi) trong database và hiển thị ra trang view nhé các bạn.

1.Tạo trang view dữ liệu

 /resources/views/user/view.blade.php

Vào thư mục /resources/views/user/ tạo file PHP view.blade.php bình thường với nội dung sau:

<table border="1">
    <thead>
        <tr>
            <th>ID</th>
            <th>Name</th>
            <th>Email</th>           
        </tr>
    </thead>
    <tbody>
        <tr>
            <td></td>
            <td></td> 
            <td></td>       
            <td>Edit | Delete</td>
        </tr>
    </tbody>
</table>

2.Thêm nội dung Controller

Thêm nội dung cho function index() của Controller User_Controller để gọi trang view xem danh sách:

{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
         return view('/user/view');
 }

Nội dung trên chỉ đơn giản là gọi trang view /user/view

3.Thêm nội dung Route

Ta thêm vào Route /routes/web.php nội dung sau:

Route::get('/user/view',[User_Controller::class, 'index']);
  • /user/view: đường dẫn tới trang xem danh sách dữ liệu.
  • User_Controller: Controller đã tạo

index: Đây là function index() trong Controller User_Controller  viết bên trên.

4. Hiển thị trang view xem danh sách dữ liệu:

Gõ đường dẫn http://localhost:8000/user/view lên trình duyệt, ta sẽ xem được nội dung sau:

 

Tiến hành lấy dữ liệu và hiển thị ra view

Để lấy dữ liệu từ database, ta cần xử lý từ Controller.

Viết lại function index từ Controller /app/Http/Controllers/User_Controller.php:

public function index()
    {
          $users = DB::select('select * from student');
          return view('user/view',['users'=>$users]);
    }

Hiển thị dữ liệu ra trang view

Dữ liệu đã lấy rồi, việc còn lại là hiển thị kết quả lấy được ra trang danh sách dữ liệu, ta viết lại trang 

<table border="1">
    <thead>
        <tr>
            <th>ID</th>
            <th>Name</th>
            <th>Email</th>           
        </tr>
    </thead>
    <tbody>
       @foreach($users as $row)
        <tr>
            <td>{{$row->id}}</td>
            <td>{{$row->name}}</td>
            <td>{{$row->email}}</td>
            <td>Edit | Delete</td>
        </tr>
        @endforeach
    </tbody>
</table>

Tới đây thì xong rồi, gõ đường dẫn http://localhost:8000/user/view lên trình duyệt, ta sẽ xem được kết quả:


5. Lời kết:

Vậy là chúng ta đã tìm hiểu xong cách sử dụng Query Builder Laravel 8 để truy xuất dữ liệu trong database và hiển thị ra view rồi đấy. Có gì thắc mắc các bạn hãy comment bên dưới nhé. Cảm ơn các bạn đã theo dõi!

Bình luận