Home >Backend Development >PHP Tutorial >How to Fix \'Specified Key Was Too Long\' Error in Laravel Migrations?

How to Fix \'Specified Key Was Too Long\' Error in Laravel Migrations?

DDD
DDDOriginal
2024-10-30 22:44:03782browse

How to Fix

Fixing "Specified Key Was Too Long" Error in Laravel Migrations

When migrating tables in Laravel, developers may encounter the "Specified key was too long" error. This is because the default maximum length for keys in MySQL is 767 bytes.

One solution is to specify the key length explicitly in the migration. For example:

Schema::create('users', function(Blueprint $table) {
    $table->increments('id');
    $table->string('email', 250)->unique('users_email_unique');
});

Laravel 5.4 and Above

In Laravel 5.4 and above, the default string length can be set in the AppServiceProvider.php file:

<code class="php">use Illuminate\Database\Schema\Builder;

public function boot()
{
    Builder::defaultStringLength(191);
}</code>

Alternatively, you can specify the length for individual columns within the migration:

<code class="php">Schema::create('users', function(Blueprint $table) {
    $table->increments('id');
    $table->string('email', 191)->unique('users_email_unique');
});</code>

The above is the detailed content of How to Fix \'Specified Key Was Too Long\' Error in Laravel Migrations?. 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