2.

Laravel マイグレーションでカラム追加・変更・削除|ALTER TABLE 構文

編集
この記事の要点
  • Laravel マイグレーションで カラムの追加 / 変更 / 削除を行う方法
  • 追加: $table->string("new_column")->nullable();
  • 変更: $table->string("name", 100)->change(); (要 doctrine/dbal
  • 削除: $table->dropColumn("old_column");
  • 位置指定: ->after("id") / ->first()
  • 本番では1 マイグレーション = 1 変更に分けるとロールバックが楽

カラム追加

既存テーブルにカラムを追加するマイグレーション:

php artisan make:migration add_phone_to_users_table --table=users
public function up() {
    Schema::table('users', function (Blueprint $table) {
        // 基本: nullable で追加(既存行があれば NULL になる)
        $table->string('phone', 20)->nullable()->after('email');

        // デフォルト値付き
        $table->string('status', 20)->default('active')->after('phone');

        // 複数カラムまとめて追加
        $table->date('birth_date')->nullable();
        $table->json('preferences')->nullable();
        $table->timestamp('last_login_at')->nullable();
    });
}

public function down() {
    Schema::table('users', function (Blueprint $table) {
        $table->dropColumn(['phone', 'status', 'birth_date', 'preferences', 'last_login_at']);
    });
}

カラム変更

doctrine/dbal パッケージが必須:

composer require doctrine/dbal

php artisan make:migration change_users_table
public function up() {
    Schema::table('users', function (Blueprint $table) {
        // 型と長さの変更
        $table->string('name', 100)->change();

        // NULL 許可に変更
        $table->string('phone', 20)->nullable()->change();

        // デフォルト値を変更
        $table->string('status', 20)->default('inactive')->change();

        // カラム名変更(doctrine/dbal 必須)
        $table->renameColumn('phone', 'phone_number');
    });
}

public function down() {
    // 必ず逆操作を書く
    Schema::table('users', function (Blueprint $table) {
        $table->string('name', 50)->change();
        $table->string('phone', 20)->nullable(false)->change();
        $table->string('status', 20)->default('active')->change();
        $table->renameColumn('phone_number', 'phone');
    });
}

カラム削除

public function up() {
    Schema::table('users', function (Blueprint $table) {
        // 単一カラム
        $table->dropColumn('temporary_field');

        // 複数カラム
        $table->dropColumn(['old_field1', 'old_field2', 'old_field3']);
    });
}

public function down() {
    // 削除前の状態を復元するため、追加 SQL を書く
    Schema::table('users', function (Blueprint $table) {
        $table->string('temporary_field', 100)->nullable();
        $table->string('old_field1')->nullable();
        $table->string('old_field2')->nullable();
        $table->string('old_field3')->nullable();
    });
}

位置指定(MySQL のみ)

メソッド動作
->after('column')指定カラムの後ろに追加
->first()テーブル先頭に追加
指定なし最後に追加(デフォルト)

PostgreSQL / SQLite はカラム位置を持たないため、after() は MySQL のみ機能します。

主要なカラム型

メソッドSQL用途
$table->id()BIGINT UNSIGNED AUTO_INCREMENT主キー
$table->string('name', 100)VARCHAR(100)短文
$table->text('body')TEXT長文
$table->integer('age')INT整数
$table->bigInteger('user_id')BIGINT大きい整数
$table->decimal('price', 10, 2)DECIMAL(10,2)金額
$table->boolean('active')TINYINT(1)真偽値
$table->date('birth_date')DATE日付
$table->datetime('event_at')DATETIME日時
$table->timestamp('created_at')TIMESTAMPタイムスタンプ
$table->json('options')JSONJSON データ
$table->enum('status', ['a','b'])ENUM列挙
$table->uuid('id')CHAR(36)UUID
$table->foreignId('user_id')BIGINT UNSIGNED + FK外部キー

修飾子

メソッド意味
->nullable()NULL 許可
->default($value)デフォルト値
->useCurrent()デフォルトを CURRENT_TIMESTAMP に
->unique()UNIQUE 制約
->index()インデックス作成
->unsigned()符号なし(数値型)
->comment('説明')カラムコメント
->charset('utf8mb4')文字セット
->collation('utf8mb4_unicode_ci')照合順序

マイグレーション実行

# 未実行のマイグレーションを順次実行
php artisan migrate

# 直近のマイグレーションを 1 つ戻す
php artisan migrate:rollback

# 直近 N 個戻す
php artisan migrate:rollback --step=3

# 全部リセット + 再実行(開発時のみ)
php artisan migrate:refresh

# 全部 drop して migration 再実行 + seeder
php artisan migrate:fresh --seed

# 状態確認
php artisan migrate:status

本番運用の注意

  • 大テーブルの ALTER は時間がかかる: 数百万行を超えると数十分ロックされる可能性。pt-online-schema-change などを検討
  • 1 マイグレーション = 1 変更に分けるとロールバックが楽
  • down() を必ず書く: 本番でロールバックできるように
  • カラム削除は段階的に: ① コード側で参照削除 → ② 本番反映 → ③ カラム削除マイグレーション、の 2 段階
  • カラム名変更: アプリのデプロイ順を考慮(先に古い名前を参照しないようコード変更してから rename)
編集
Post Share
子ページ

子ページはありません

同階層のページ
  1. テーブルの作成と定義の変更
  2. カラムの追加、変更、削除方法
  3. データ型とカラム修飾子
  4. デフォルト値の設定