Laravel migrate でカラム名の変更

どんな記事?

Laravel 7.30.4でデータベースのmigrateを行う際、カラム名の変更の仕方がわからなかったのでメモ。
デフォルトではカラム名の変更は出来ないんですね。
ですが出来る方法を発見しました。

doctrine/dbalのインストール

composer require doctrine/dbal だと何故か
Class 'Doctrine\DBAL\Driver\PDOMySql\Driver’ not found
になってしまうようですので2系をインストールします。

composer require "doctrine/dbal:2.*"

これでカラム名が変更できるようになりました。

マイグレーションファイルの作成

今回はusersテーブルの"name"カラムを"name1″に変更します。
早速マイグレーションファイルを作成します。

php artisan make:migration rename_name_to_name1_on_users_table --table=users
Created Migration: 2021_08_20_103329_rename_name_to_name1_on_users_table

マイグレーションファイルの設定

renameColumn('name', 'name1');
        });
    }
    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::table('users', function (Blueprint $table) {
            $table->renameColumn('name1', 'name');
        });
    }
}

こんな感じに書き換えます。

マイグレート

php artisan migrate
Migrating: 2021_08_20_103329_rename_name_to_name1_on_users_table
Migrated:  2021_08_20_103329_rename_name_to_name1_on_users_table (0.04 seconds)

これで完成です。

Laravel

Posted by bistro