Laravelのafter()メソッドを使用した段階的なカラム追加は、本番環境でよく発生する問題を解決します。
本番環境で新しいカラムを追加する際、既存のレコードに対してNOT NULL制約を設定すると、データベースエラーが発生することがあります。
// マイグレーション 1: まずNULL許容で追加
public function up()
{
Schema::table('users', function (Blueprint $table) {
$table->string('phone_number')
->nullable()
->after('email');
});
}
// マイグレーション 2: デフォルト値を設定
public function up()
{
DB::table('users')
->whereNull('phone_number')
->update(['phone_number' => '未設定']);
}
// マイグレーション 3: NOT NULL制約を追加
public function up()
{
Schema::table('users', function (Blueprint $table) {
$table->string('phone_number')
->nullable(false)
->change();
});
}
この技術により、大規模なデータベースでも安全にスキーマ変更が可能になります。