การเพิ่ม, ลบ, และแก้ไขคอลัมน์ใน Laravel ด้วย Migration
ก่อนอื่น ถ้าต้องการแก้ไขตารางที่มีอยู่แล้ว ต้องใช้คำสั่ง make:migration
โดยเพิ่ม --table=table_name
เพื่อระบุว่าจะแก้ไขตารางไหน
1️⃣ การเพิ่มคอลัมน์
🔹 ตัวอย่าง: เพิ่มคอลัมน์ phone
และ address
ในตาราง users
php artisan make:migration add_phone_and_address_to_users_table --table=users
ไฟล์ Migration ที่สร้างขึ้นจะอยู่ใน database/migrations/
และมีโค้ดเริ่มต้น
✏️ แก้ไขไฟล์ Migration:
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration {
public function up()
{
Schema::table('users', function (Blueprint $table) {
$table->string('phone')->nullable()->after('email');
$table->text('address')->nullable()->after('phone');
});
}
public function down()
{
Schema::table('users', function (Blueprint $table) {
$table->dropColumn(['phone', 'address']);
});
}
};
📌 คำอธิบาย:
->nullable()
→ ทำให้คอลัมน์สามารถมีค่าNULL
ได้->after('email')
→ กำหนดให้คอลัมน์phone
อยู่หลังemail
✅ รัน Migration:
php artisan migrate
2️⃣ การลบคอลัมน์
🔹 ตัวอย่าง: ลบคอลัมน์ phone
ออกจากตาราง users
php artisan make:migration remove_phone_from_users_table --table=users
✏️ แก้ไขไฟล์ Migration:
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration {
public function up()
{
Schema::table('users', function (Blueprint $table) {
$table->dropColumn('phone');
});
}
public function down()
{
Schema::table('users', function (Blueprint $table) {
$table->string('phone')->nullable();
});
}
};
✅ รัน Migration:
php artisan migrate
3️⃣ การแก้ไขคอลัมน์
📌 การแก้ไขคอลัมน์ใน Laravel ต้องใช้ doctrine/dbal
package
💡 ติดตั้ง package ก่อน (หากยังไม่ได้ติดตั้ง)
composer require doctrine/dbal
🔹 ตัวอย่าง: แก้ไขคอลัมน์ address
จาก text
เป็น string
และเพิ่มค่าเริ่มต้น (default)
php artisan make:migration modify_address_in_users_table --table=users
✏️ แก้ไขไฟล์ Migration:
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration {
public function up()
{
Schema::table('users', function (Blueprint $table) {
$table->string('address', 255)->default('Unknown')->change();
});
}
public function down()
{
Schema::table('users', function (Blueprint $table) {
$table->text('address')->nullable()->change();
});
}
};
✅ รัน Migration:
php artisan migrate
สรุป
🔹 เพิ่มคอลัมน์ → Schema::table()->addColumn()
🔹 ลบคอลัมน์ → Schema::table()->dropColumn()
🔹 แก้ไขคอลัมน์ → Schema::table()->change()
(ต้องใช้ doctrine/dbal
)
🛠 เครื่องมือ Migration ทำให้สามารถจัดการโครงสร้างฐานข้อมูลได้ง่ายและมีระเบียบมากขึ้น โดยไม่ต้องใช้ SQL โดยตรง 🚀