Laravel Migration Error: Unique Key Length Exceeds Limit
When attempting to migrate a users table in Laravel using a migration, developers may encounter the error: "[SQLSTATE[42000]: Syntax error or access violation: 1071 Specified key was too long; max key length is 767 bytes." This error typically arises when the specified unique key is longer than the maximum allowable length.
Problem Statement
The provided migration attempts to create a users table with a unique key on the email column. However, the email column is specified to have a length of 320 characters, exceeding the maximum length limit.
Solution
1. Reduce Email Column Length
Reduce the length of the email column to a smaller value, such as 250 or the default of 191 characters. Adjust the migration as follows:
Schema::create('users', function(Blueprint $table) { // ... $table->string('email', 250); // Update the email column length // ... });
2. Set Default String Length (Laravel 5.4 )
If you're using Laravel 5.4 or higher, you can set a default string length in the boot method of the AppServiceProvider.php file:
public function boot() { Builder::defaultStringLength(191); }
This will set a default length of 191 characters for all string columns created in migrations, ensuring that unique keys do not exceed the allowable length.
The above is the detailed content of Laravel Migration Error: How to Fix 'Unique Key Length Exceeds Limit'?. For more information, please follow other related articles on the PHP Chinese website!