2025年6月29日 星期日

Laravel 12 Model 資料庫中的資料表,並提供與資料庫互動的介面

相關系列文章:

         在Laravel 中,Model 代表資料庫中的資料表,並提供與資料庫互動的介面。 
它使用Eloquent ORM,讓開發者可以更直觀地操作資料庫,而不需要寫大量的SQL 語法。 Model 實體對應到資料表的一列數據,可以進行新增、讀取、更新和刪除等操作。

一、建立一個 Student 的 Model
php artisan make:model Student


二、加上-mc 建立一個Teachers 的 Model 
php artisan make:model Teachers -mc

就會建立三個,分別是 Model、Controller、Migration
在 2025_06_29_113017_create_teachers_table.php , 可以加上
            $table->string('name');

如下圖:

然後,命令列輸入
 php artisan migrate

並隨意增加幾個數據,

1.在 routes/web.php 寫入
Route::get('teachers',function(){
    return Teachers::all();
});

接下來進行測試:
php artisan serve
在網頁網址上打上:http://127.0.0.1:8000/teachers/


通常我們不會像上述的方法來寫,而是向下面的方式來寫:
2.在 routes/web.php 寫入
Route::get('teachers',[TeachersController::class,'index']);
在/app/http/controllers/TeachersController.php 寫入
    public function index()
    {
        return Teachers::all();
    }

在網頁網址上打上http://127.0.0.1:8000/teachers/,一樣可以看到

接下來,增加一名老師,名叫Test Name,並觀察資料庫的變化
3.在 routes/web.php 寫入
Route::get('add-teacher',[TeachersController::class,'add']);

在/app/http/controllers/TeachersController.php 寫入

    public function add() {
        $item = new Teachers();
        $item->name = 'Test Name';
        $item->save();

        return 'Added Successfully';
    }

啟用伺服器
php artisan serve
在網址打上 127.0.0.1:8000/add-teacher
                
然後在資料庫,可發現

接下來,如何在網頁上取得這位老師的資料,並呈現出來。
4.在/app/http/controllers/TeachersController.php 寫入

    public function show($id) {
        $item = Teachers::findOrFail($id);
        return $item;
    }


 routes/web.php 寫入
Route::get('show-teacher/{id}',[TeachersController::class,'show']);
接下來,在網址列輸入http://127.0.0.1:8000/show-teacher/7

接下來,要如何更新這位老師的資料,並呈現出來
5.在/app/http/controllers/TeachersController.php 寫入
    public function update($id) {
        $item = Teachers::findOrFail($id);
        $item->name = 'Updated Teacher';
        $item->update();
        return 'updated Successfully';
    }
 routes/web.php 寫入
Route::get('update-teacher/{id}',[TeachersController::class,'update']);
在資料庫的資料為

接下來,要來刪除這筆資料
6.在/app/http/controllers/TeachersController.php 寫入
    public function delete($id) {
        $item = Teachers::findOrFail($id);
        $item->delete();
        return 'Deleted Successfully.';
    }
 routes/web.php 寫入
Route::get('delete-teacher/{id}', [TeachersController::class, 'delete']);
在資料庫

沒有留言:

張貼留言

laravel 資料庫資料填充工廠入門

相關系列文章: 1. 在 windows 10 安裝 laravel 12 studentManagement環境與設定 2. laravel 12 route 路由 3. laravel 12 Blade Templates 網頁模版 4. laravel 12 Control...