Laravel 从 5.4 版本开始, 默认使用 utf8mb4. 如果执行 php artisan migrate 命令报 SQLSTATE[42000]: Syntax error or access violation: 1071 Specified key was too long; 之类的语法错误, 就需要做些特殊处理.
# php artisan migrate --seedMigration table created successfully.Migrating: 2014_10_12_000000_create_users_tableIn Connection.php line 664:SQLSTATE[42000]: Syntax error or access violation: 1071 Specified key was too long; max key length is 1000 bytes (SQL: alter table `users` add unique `users_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 1000 bytes解决方案
限制 migrate 生成的默认字符串长度为 191: 在
App\Providers\AppServiceProvider 的 boot() 方法里添加配置:
use Illuminate\Support\Facades\Schema;
public function boot(){
Schema::defaultStringLength(191);
}
修改 app/config/database.php 对应数据库配置:'charset' => 'utf8mb4',
// 改成 utf8'collation' => 'utf8mb4_unicode_ci', // 改成 utf8_unicode_ci升级 MySQL 版本到 5.5.3 以上原因
Laravel 从 5.4 版本开始, 默认使用 utf8mb4编码.
MySQL 支持的 utf8 编码最大字符长度为 3 字节,如果遇到 4 字节的宽字符就会出现插入异常.
默认情况下 MySQLInnoDB 引擎单一字段索引的长度是 767 字节, 如编码是 utf8mb4 最大可能占 4 个字节(767/4 约等于 191), 如果超出 191 就报错了.