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
Release: 2024-12-01 16:31:10
Original
280 people have browsed it

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);
Copy after login

Alternatively, you can use the default length:

$table->string('email');
Copy after login

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);
}
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template