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

How to Solve Laravel Migration Error: Unique Key Length Limit Exceeded?

Linda Hamilton
Release: 2024-11-30 00:29:09
Original
826 people have browsed it

How to Solve Laravel Migration Error: Unique Key Length Limit Exceeded?

Laravel Migration Error: Unique Key Length Limit Exceeded

In Laravel, when creating a migration to add a unique key to a column with an overly long string, you may encounter the following error:

[Illuminate\Database\QueryException] SQLSTATE[42000]: Syntax error or access violation: 1071 Specified key was too long; max key length is 767 bytes
Copy after login

This error can often be resolved by specifying a smaller length for the column. The default length for a string is 250 characters, which should be adequate for most email addresses and other typical strings.

In your specific migration, you have defined the email column as a string with a length of 320. Try reducing this length to 250 or the default value:

Schema::create('users', function (Blueprint $table) {
    $table->string('email', 250); // or $table->string('email');
Copy after login

If you are still experiencing the error even after adjusting the column length, you can try setting a default string length for your database. In Laravel 5.4 and later, you can achieve this by adding the following to your AppServiceProvider.php file:

use Illuminate\Database\Schema\Builder;

public function boot()
{
    Builder::defaultStringLength(191);
}
Copy after login

This will set the default string length to 191 characters for all new columns created in migrations.

The above is the detailed content of How to Solve Laravel Migration Error: Unique Key Length Limit 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