Laravel 迁移数据库发生 Specified key was too long 错误

在 Laravel 经历 5.1 到 5.5 版本升级的过程中,追加了对于 emoji 字符的支持。因此,其默认的数据库字符集也换成了 utf8mb4。但是,如果服务器的 MySQL 数据库版本低于 5.7.7(或 Mariadb 低于 10.2.2),就会遇到以下的错误:

1
2
3
4
5
6
7
8
9
10
11
12
[[email protected] Andromeda]# php artisan migrate
Migration table created successfully.

In Connection.php line 664:

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 `user
s_email_unique`(`email`))


In Connection.php line 458:

SQLSTATE[42000]: Syntax error or access violation: 1071 Specified key was too long; max key length is 767 bytes

根据 Laravel 文档1 中的描述:

you may need to manually configure the default string length generated by migrations in order for MySQL to create indexes for them. You may configure this by calling the Schema::defaultStringLength method within your AppServiceProvider

也就是说,要在 AppServiceProviderboot() 中,通过调用 Schema::defaultStringLength(),来修改默认字符串长度,例如这样:

1
2
3
4
5
6
7
8
9
10
11
use Illuminate\Support\Facades\Schema;

/**
* Bootstrap any application services.
*
* @return void
*/
public function boot()
{
Schema::defaultStringLength(191);
}

除此之外,文档中也提到,还可以修改数据库的 innodb_large_prefix 选项来避免报错。

参考链接

[1] Laravel Documentation - migrations
[2] Eric L. Barnes, Laravel 5.4: Specified key was too long error