LoginSignup
3
0

More than 5 years have passed since last update.

Schema で morphs のカラムを作るとインデックス長が制限を超えてしまう場合の対処方法

Last updated at Posted at 2018-01-01

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();
});
3
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
0