1. Route
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
<?php // Sửa trong file Routes/web.php // Cấu trúc Route::METHOD(path_string,HANDLE_FUNCTION); // Giả sử Link vào trang -- http://localhost/t1904a_laravel/public/xin-chao -- như sau Route::get("/xin-chao",function(){ echo "Chào tất cả mọi người"; }); // Thực tế việc của Route là điều hướng đến Controller // Ở dưới thể hiện điều hướng đến Controller, cụ thể là hàm "classRoom" trong WebController tại thư mục app/Http/Controller Route::get("/danh-sach-lop-hoc","WebController@classRoom"); // Ở dưới thể hiện điều hướng đến Controller, cụ thể là hàm "listing" trong WebController tại thư mục app/Http/Controller, và có nhận thêm biến {id} ở listing. Route::get("/danh-muc/{id}","WebController@listing"); // |
2. Controller
- Tạo file WebController trong thư mục app/Http/Controller bằng Terminal
1 |
php artisan make:controller WebController |
- Thêm dữ liệu cho Controller
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; class WebController extends Controller { //tạo dữ liệu để thử public function classRoom(){ $students = [ [ "id" => 1, "name"=> "Nguyễn Thị Ninh", "mark"=>9 ], [ "id" => 2, "name"=> "Nguyễn Thế Anh", "mark"=>3 ], [ "id" => 3, "name"=> "Nguyễn Thị Nụ", "mark"=>7 ], ]; return view("student_listing",['students'=>$students]); // Ở trên thể hiện điều hướng đến resoures/views/student_listing.blade.php // Và bắn thêm biến students sang bên đó } //lấy thêm biến $id public function listing($id){ $products = Product::where("category_id",$id)->take(20)->orderBy('created_at','desc')->get(); return view("listing",['products'=>$products]); } |
3. View
- Tại resoures/views/... tạo 1 file student_listing.blade.php với nội dung như sau
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 |
<!doctype html> <html lang="en"> <head> <link rel="stylesheet" href={{asset("css/style.css")}}> </head> <header> <ul class="nav nav-tabs"> <li class="nav-item"><a class="nav-link active" href="{{url("/")}}">Home</a></li> @foreach(\App\Category::all() as $c) <li class="nav-item"><a class="nav-link" href="{{url("danh-muc/{$c->id}")}}">{{$c->category_name}}</a></li> @endforeach </ul> </header> <body> <main> <h1>Danh sách sinh viên</h1> <table class="table"> <thead> <th>ID</th> <th>Name</th> <th>Email</th> <th>Mark</th> </thead> <tbody> <?php foreach ($students as $s):?> <tr> <td><?php echo $s['id'];?></td> <td><?php echo $s['name'];?></td> <td><?php echo $s['email'];?></td> <td><?php echo $s['mark'];?></td> </tr> <?php endforeach; ?> </tbody> </table> </main> </body> </html> //Bây giờ có thể vào http://localhost/t1904a_laravel/public/danh-sach-lop-hoc để xem kết quả |