错误提示:

php artisan migrate创建表时提示如下错误

1
2
3
[Illuminate\Database\QueryException] SQLSTATE[42000]: Syntax error or access violation: 1071 Specified key was too long; max key length is 767 bytes (SQL: alter tabl e users add unique users_email_unique(email))
[PDOException] SQLSTATE[42000]: Syntax error or access violation: 1071 Specified key was too long; max key length is 767 bytes

运行环境:

Laravel = 5.4

PHP = 7.0

MariaDB = 10. 1.21

原因:

Laravel 使用 utf8mb4 作为默认编码,原有是想数据库支持emoji表情,但是默认编码是4个字节,数据库支持最大767个bytes,所以最大长度767/4=191,string类型字段默认长度255超过了191。

解决方法:

1.基础方法

修改/app/Providers/AppServiceProvider.php

1
2
3
4
5
6
use Illuminate\Support\Facades\Schema; //Import Schema
function boot()
{
Schema::defaultStringLength(191); //Solved by increasing StringLength
}

修改了默认长度。

2.更优方法

了解并修改数据库的innodb_large_prefix选项。

3.最好办法

Mysql升级到5.7.7以及更新版本。

MariaDB升级到10.2.2以及更新版本。