Migration adalah version control untuk database — melacak perubahan skema secara terstruktur.
Membuat migration:
php artisan make:migration create_users_table
File migration:
return new class extends Migration
{
public function up(): void
{
Schema::create("users", function (Blueprint $table) {
$table->id(); // BIGINT PRIMARY KEY AUTO_INCREMENT
$table->string("name"); // VARCHAR(255)
$table->string("email")->unique(); // VARCHAR(255) UNIQUE
$table->integer("age")->nullable(); // INT NULL
$table->boolean("active")->default(true);
$table->timestamps(); // created_at, updated_at
});
}
public function down(): void
{
Schema::dropIfExists("users");
}
};
Tipe kolom yang sering dipakai:
| Method | SQL Type |
|---|---|
$table->id() |
BIGINT PRIMARY KEY |
$table->string("col") |
VARCHAR(255) |
$table->text("col") |
TEXT |
$table->integer("col") |
INT |
$table->boolean("col") |
TINYINT(1) |
$table->decimal("col", 10, 2) |
DECIMAL(10,2) |
$table->timestamps() |
created_at + updated_at |
$table->foreignId("user_id") |
BIGINT + foreign key |
Menjalankan migration:
php artisan migrate # Jalankan semua
php artisan migrate:rollback # Undo terakhir
php artisan migrate:fresh # Drop semua + migrate ulang