一、Controller 控制器
1.指令建立控制器
php artisan make:controller StudentController
2.在app/Http/Controllers/StudentController.php
新增一個函式
public function index() {
return "hello from controller.";
}
Route::get('students',[StudentController::class,'index']);
4.網址列打上http://127.0.0.1:8000/StudentController
就可以看到
二、兩個同樣控制器的Route,該如何合併成一個Route
1.在app/Http/Controllers/StudentController.php
新增一個函式
public function aboutus(){
return 'Code with Mark.';
}
新增一條規則
Route::get('aboutus', [StudentController::class, 'aboutus']);
3.網址列打上http://127.0.0.1:8000/aboutus
就可以看到

在routes/web.php 合併成一個Route
Route::controller(StudentController::class)->group(function () {
Route::get('student', 'index');
Route::get('aboutus', 'aboutus');
});
5.網址列打上http://127.0.0.1:8000/aboutus、http://127.0.0.1:8000/student
三、傳送資料到控制器
1.在routes/web.php |
修改
Route::get('aboutus/{id}/{name}','aboutus');
2.在app/Http/Controllers/StudentController.php修改
public function aboutus($id,$name){
return 'ID No ' . $id .' Name ' . $name;
}

3.網址列打上http://127.0.0.1:8000/aboutus/1/Mark
四、傳送資料到視圖View
1.在routes/web.php |
修改
Route::controller(StudentController::class)->group(function () {
Route::get('student', 'index');
Route::get('aboutus/{id}/{name}','aboutus');
});
2.在app/Http/Controllers/StudentController.php
修改
public function aboutus($id,$name){
return view('aboutus', compact('id', 'name'));
}
修改
4.網址列打上http://127.0.0.1:8000/aboutus/1/Mark
<section>
<h2>About Us</h2>
<p>This is simple HTML and CSS template to start your project.</p>
<p>Name:{{$name}}</p>
<p>ID:{{$id}}</p>
</section>
其中resources/layouts/app.blade.php
resources/aboutus.blade.php