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
Linda HamiltonOriginal
2024-11-30 00:29:09840browse

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

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');

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);
}

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!

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