How to solve Syntax error or access violation: 1071 Specified key was too long?
SQLSTATE[42000]: Syntax error or access violation: 1071 Specified key was too long; max key length is 1000 bytes (Connection: mysql, SQL: create table password_reset_tokens
(email
varchar(255) not null, token
varchar(255) not null, created_at
timestamp null, primary key (email
)) default character set utf8mb4 collate ‘utf8mb4_unicode_ci’)
It looks like you’re encountering a SQL error when running a migration in Laravel due to a key length limit in MySQL. This issue typically arises when Laravel tries to create a key that exceeds the maximum length allowed by MySQL.
The error message specifically states: “Specified key was too long; max key length is 1000 bytes.” This happens because Laravel, by default, uses the utf8mb4 character set for database encoding, which allows for characters that require up to four bytes per character.
Here are a few approaches you can take to resolve this:
Update MySQL Configuration
You can modify the MySQL configuration to increase the maximum index length allowed. You would need to set the innodb_large_prefix
option to ON
and the innodb_file_format
option to Barracuda
. However, this may not be feasible if you don’t have control over the MySQL server settings.
Change Default String Length
In your AppServiceProvider.php
, within the boot
method, you can set a default string length for your schema. This will limit the length of indexes created by Laravel. Here’s how you can do it:
use Illuminate\Support\Facades\Schema;
public function boot()
{
Schema::defaultStringLength(191);
}
This will set the default string length to 191 characters, which is compatible with the utf8mb4 character set and avoids the key length issue.
Specify Key Length
You can manually specify the length of keys in your migrations. For example:
$table->string('email', 191)->primary();
This sets the length of the email
column to 191 characters, which should prevent the error. Choose the approach that best fits your project requirements and constraints.