Error report of migrate in Laravel 5.4: Solution of Specified key was too long error

  • 2021-08-10 07:31:46
  • OfStack

Preface

As we all know, we often do projects in teams, and everyone is in their own local database. If you have ever had colleagues manually add fields to the database structure, database migration can solve your problem.

Not only that, when deploying online, it also avoids the trouble of manually importing the database or manually modifying the data structure. Data migration helps you maintain the data structure conveniently.

However, convenience will also be accompanied by a number of problems. The following article will introduce in detail the solution to the error of migrate in Laravel5.4, Specified key was too long error. Let's not say much below. Let's take a look at the detailed introduction.

Find a problem

Laravel 5.4 defaults to utf8mb4 character encoding instead of the previous utf8 encoding. So run php artisan migrate The following error occurs:


[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

The root of the problem

MySql supports utf8 encoding with a maximum character length of 3 bytes. If a wide character of 4 bytes is encountered, an insertion exception will occur. The 3-byte UTF-8 maximum encoded Unicode character is 0xffff, which is the basic multilingual plane (BMP) in Unicode. Therefore, Unicode characters in non-basic multilingual planes, including Emoji expressions (Emoji is a special Unicode encoding), cannot be stored using utf8 character set of MySql.

This should be one of the reasons why Laravel 5.4 switched to the 4-byte length utf8mb4 character encoding. Note, however, that utf8mb4 character encoding is supported only after MySql 5.5. 3 (see version: selection version ();) . If the MySql version is too low, a version update is needed.

Note: If you are upgrading from Laravel 5.3 to Laravel 5.4, you do not need to switch the character encoding.

Solve a problem

Upgrade MySql version to 5.5. 3 or above. Manually configure the default string length generated by the migration command migrate, which is called in AppServiceProvider Schema::defaultStringLength Method to implement configuration:

 use Illuminate\Support\Facades\Schema;

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

Summarize


Related articles: