Troubleshooting Laravel Migration Error: Unique Key Length Exceeded
When attempting to create a unique key for an email column in Laravel, you may encounter the following error:
[IlluminateDatabaseQueryException] SQLSTATE[42000]: Syntax error or access violation: 1071 Specified key was too long; max key length is 767 bytes
Although you have specified the index key as the second parameter to the unique() method, the error persists. This is likely due to the length of the email column.
Solution for Laravel versions prior to 5.4:
To resolve this error, reduce the length of the email column. The default length is 250 characters, so modify the following line in your migration:
$table->string('email', 250);
Alternatively, you can use the default length:
$table->string('email');
Solution for Laravel 5.4 and above:
In Laravel 5.4, you can set a default string length to avoid this error. In your AppServiceProvider.php file, add the following code to the boot method:
use Illuminate\Database\Schema\Builder; public function boot() { Builder::defaultStringLength(191); }
This will ensure that all string columns use a maximum length of 191 characters.
The above is the detailed content of How to Fix Laravel Migration Error: Unique Key Length Exceeded?. For more information, please follow other related articles on the PHP Chinese website!