2025年6月6日 星期五

laravel 12 Controller 控制器

Controller 用來整理請求邏輯,將相關邏輯放在一個類別裡。 例如, UserController 處理所有與使用者有關的請求。 包括顯示 (showing)、創建 (creating)、更新 (updating)和刪除 (deleting)使用者等等。

一、Controller 控制器
1.指令建立控制器

php artisan make:controller StudentController 

 
2.在app/Http/Controllers/StudentController.php
新增一個函式
    public function index() {
        return "hello from controller.";
    }
可以看到

3.在routes/web.php
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.';
    }
2.在routes/web.php
新增一條規則
Route::get('aboutus', [StudentController::class, 'aboutus']);


3.網址列打上http://127.0.0.1:8000/aboutus
就可以看到

4.兩個同樣控制器的Route,合併成一個Route
在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'));
    }

3.在resources/aboutus.blade.php
修改
                <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
4.網址列打上http://127.0.0.1:8000/aboutus/1/Mark

沒有留言:

張貼留言

只要點兩下,就可以將資料夾input內的所有Word通通轉成一個PDF

系列文章: 1. python 不管何時何地,只要點兩下,資料夾內的所有pdf都會合併成一個pdf https://skjhcreator.blogspot.com/2022/06/pythonpdfpdf.html 2. python 只要點兩下,分別對各資料夾內的pdf合併,...