2017年2月5日 星期日

laravel 1071 Specified key was too long; max key length is 767 bytes 解決方法

        laravel new 一個新專案之後,在.env用好資料庫設定,接著執行php artisan migrate的時候,拋出了兩個例外:

  [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  

        可以看到共通點就是Specified key was too long; max key length is 767 bytes。

        因為laravel5.4用的是utf8mb4編碼,這種編碼跟默認的uft8編碼差別就在於utf8編碼最多支援到3個字節,而utf8mb4可以支援到四個字節,所以utf8mb4可以支援四個字節的emojis儲存進資料庫,mb4指的就是「most bytes 4」,而utf8mb4同時也支援許多的漢語難字。

        但在5.7.7之前的Mysql版本,以及10.2.2之前的MariaDB版本必須要手動調整預設的字串長度讓MySQL可以為他們新增索引。

        實際做法是在AppServiceProvider.php裡面加兩行程式碼:

<?php
namespace App\Providers;

use Illuminate\Support\ServiceProvider;

// 1
use Illuminate\Support\Facades\Schema;

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

    /**     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        //    
    }
}

        引入Schema之後再去呼叫defaultStringLength去更改預設字串長度就行了。


參考資料:


1 則留言:

  1. Best Casino Restaurants in the Bay Area | MapyRO
    Find your ideal location 진주 출장샵 near 울산광역 출장안마 Fremont Street, Bay Area Casino 이천 출장샵 in Bay Area and enjoy dining, 사천 출장안마 drinks, and more at the best 안양 출장마사지 spot in

    回覆刪除