Home >Database >Mysql Tutorial >How to Fix Laravel Migration Error: Unique Key Length Exceeded?

How to Fix Laravel Migration Error: Unique Key Length Exceeded?

Linda Hamilton
Linda HamiltonOriginal
2024-12-01 16:31:10280browse

How to Fix Laravel Migration Error: Unique Key Length Exceeded?

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn