相關系列文章:
在Laravel 中,Model 代表資料庫中的資料表,並提供與資料庫互動的介面。 它使用Eloquent ORM,讓開發者可以更直觀地操作資料庫,而不需要寫大量的SQL 語法。 Model 實體對應到資料表的一列數據,可以進行新增、讀取、更新和刪除等操作。
一、建立一個 Student 的 Model
php artisan make:model Student
在 2025_06_29_113017_create_teachers_table.php , 可以加上
$table->string('name');
如下圖:
php artisan migrate
並隨意增加幾個數據,
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';
}
在網址打上 127.0.0.1:8000/add-teacher
然後在資料庫,可發現
接下來,如何在網頁上取得這位老師的資料,並呈現出來。
4.在/app/http/controllers/TeachersController.php 寫入
public function show($id) {
$item = Teachers::findOrFail($id);
return $item;
}
接下來,要如何更新這位老師的資料,並呈現出來
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.';
}