Laravel 5.4: Specified key was too long error

Laravel 5.4 made a change to the default database character set, and it’s now utf8mb4
which includes support for storing emojis. This only affects new applications and as long as you are running MySQL v5.7.7 and higher you do not need to do anything.
For those running MariaDB or older versions of MySQL you may hit this error when trying to run migrations:

[Illuminate\Database\QueryException]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
))
[PDOException]SQLSTATE[42000]: Syntax error or access violation: 1071 Specified key was too long; max key length is 767 bytes

As outlined in the Migrations guide to fix this all you have to do is edit your AppServiceProvider.php
file and inside the boot method set a default string length:

use Illuminate\Support\Facades\Schema;
public function boot()
{ 
    Schema::defaultStringLength(191);
}

After that everything should work as normal.

但是对于 Laravel auth form 验证字段很多都这样写:

protected function validator(array $data)
    {
        return Validator::make($data, [
            'name' => 'required|string|max:255',
            'email' => 'required|string|email|max:255|unique:users',
            'password' => 'required|string|min:6|confirmed',
        ]);
    }

我们需要把所有的 255 改为 191 ? 修改默认字符串的长度显然不是最佳的解决方案。

实际上这个问题出在 MySQL本身,对 MySQL 启用 innodb_large_prefix 选项即可。

在 Debian 中过程如下:

  • 创建单独的配置文件
$ sudo touch /etc/mysql/conf.d/innodb_large_prefix.cnf
  • 在配置文件中写入如下内容:
[mysqld]
# innodb settings
innodb_large_prefix=1
innodb_purge_threads=1
innodb_file_format = Barracuda
innodb_file_per_table = 1
  • 重启 MySQL
$ sudo systemctl restart mysql

你可能感兴趣的:(Laravel 5.4: Specified key was too long error)