laravel を mysql で使っていると migration
を実行した時に下記のようなエラーが発生することが有る。
SQLSTATE[42000]: Syntax error or access violation: 1071 Specified key was too long;
max key length is 767 bytes (SQL: alter table `users` add unique `users_email_unique`(`email`))
これは InnoDB の最大インデックス長を超えたためなのでカラム サイズを小さくする必要がある。特に文字コードを utf8mb4
にしているとデフォルトの string 長が 255 文字で有るためにしばしば発生する。
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('email')->unique();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
そんな時は、文字列長を 191 以下にすると解決可能です。
$table->string('email', 191)->unique();
ところが、morphs
を指定しているとメソッドの内部で string
をコールしているため直接変更が出来ない。
そんな時は defaultStringLength
を使って変更してあげると回避できる。
Schema::create('notifications', function (Blueprint $table) {
$table->uuid('id')->primary();
$table->string('type');
Schema::defaultStringLength(191);
$table->morphs('notifiable');
Schema::defaultStringLength(255);
$table->text('data');
$table->timestamp('read_at')->nullable();
$table->timestamps();
});