昨天我們學了 Eloquent ORM 操作資料庫,今天要來認識 Migration —— Laravel 幫我們管理資料表的「時光機」
想像你的資料表是一棟大樓,Migration 就是它的「建築藍圖」:
為什麼要用 Migration?
php artisan make:migration create_products_table
這會在 database/migrations/
建立一個檔案,例如:
2025_08_12_123456_create_products_table.php
編寫 Migration
打開檔案,在 up() 方法定義資料表結構:
public function up()
{
Schema::create('products', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->integer('price');
$table->timestamps();
});
}
在 down() 方法定義回滾動作:
public function down()
{
Schema::dropIfExists('products');
}
執行 Migration
php artisan migrate
執行後會在資料庫建立 products 表格
新增欄位
假設要在 products 加上 description 欄位:
php artisan make:migration add_description_to_products_table --table=products
在 up() 中加上:
$table->text('description')->nullable();
再執行:
php artisan migrate
回滾 Migration
撤銷最近一次 Migration:
php artisan migrate:rollback
清空所有資料表並重新執行:
php artisan migrate:fresh