Laravel 6 migrate 出現 1071錯誤

JungR
JungR
Nov 1 · 3 min read

當我們在使用Laravel 6.0版本時,php artisan migrate 會出現以下錯誤:

Syntax error or access violation: 1071 Specified key was too long;
php artisan migrate errors

原因是Laravel在5.4版本以後,將原本資料庫的編碼從utf8改為utf8mb4,有兩種解法,依照需求來做修改。關於utf8與utf8mb4的差別如下:

utf8 多了 mb4 有甚麼好處?
MySQL 在 5.5.3 版本之後增加了 utf8mb4 字符編碼,mb4即most bytes 4。
簡單說 utf8mb4 是 utf8 的超集並完全兼容 utf8,能夠用四個字元儲存更多的字符。

* utf8 跟 utf8mb4 具有相同的儲存特性:相同的代碼值,相同的編碼,相同的長度。
* 不過使用 utf8mb4 可以讓1個字符最多可有 4 位元,所以能支持更多的位元集。
* utf8mb4 可以向下兼容 utf8,而且比 utf8 可以表示更多的字串。此外,將編碼改為 utf8mb4 外不需要做其他轉換。

utf8 已經能夠存下大部分的中文字,那為什麼還要改成使用 utf8mb4 呢?
原因為 mysql 支持的 utf8 編碼最大長度為 3 位元(Unicode 字符是0xffff)稱之Unicode 的基本多文種平面(BMP),但如果遇到 4 位元的寬字串就會插入異常了,也就是任何不在基本多文本平面的 Unicode 字串,都無法使用 Mysql 的 utf8 字串集儲存。

如果要開發討論區或是大型跨國網頁程式,為了擁有更加的文字兼容性,就可以使用 utf8mb4。然而,在 CHAR 類型數據,utf8mb4 會比 utf8 多消耗一些空間,故 Mysql 官方指出,可使用 VARCHAR 替代 CHAR。

reference:[MySQL] 為什麼 MySQL 要設定用 UTF8MB4 編碼 UTF8MB4_UNICODE_CI

解法1. 修改 config/database.php,把 connections中的 mysql設定之 charsetcollation從utf8mb4改為utf8即可,或是按照你的需求修改。

- 'charset' => 'utf8mb4',
- 'collation' => 'utf8mb4_unicode_ci',
+ 'charset' => 'utf8',
+ 'collation' => 'utf8_unicode_ci',

解法2. 修改 app/Providers/AppServiceProvider.php ,在 boot 功能中設定默認的字串長度即可。

+ use Illuminate\Support\Facades\Schema;/**
* Bootstrap any application services.
*
* @return void
*/
public function boot() {
+ Schema::defaultStringLength(191);
}

修改完畢之後,重新執行 php artisan migrate 就可以成功囉!

JungR

Written by

JungR

Attitude determines everythings!

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade