Skip to main content

Fix “Specified key was too long error” in Laravel

If you get the error “Specified key was too long; max key length is 767 bytes” when trying to run a migration in Laravel, it’s because your database table uses the InnoDB storage engine and you’re using a utf8mb4 character set.

If you’re running a migration on an older version of Laravel 5 and MySQL/MariaDB, 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 (SQL: alter table users add unique users_email_uniq(email))

This is because, prior to Laravel 5.4, the default database character set was latin1, which allows only a maximum of 191 characters in a varchar field. If you use a newer version of MySQL (v5.7.7 and higher) or MariaDB (10.2.2 and higher), you will not experience this error. A newer version of Laravel set utf8mb4 as the default charset for the database, which allows to store Unicode characters and increases the character max to 255.

Here are some methods to fix for the older version:

In AppServiceProvider.php, change the defaultStringLength() method:

use Illuminate\Support\Facades\Schema;

public function boot()

Define length when creating table

$table->string('username', 255);
$table->string('email', 255);

Set default charset to utf8mb4 in config/database.php file:

'mysql' => [
    'driver' => 'mysql',
    'host' => env('DB_HOST', ''),
    'port' => env('DB_PORT', '3306'),
    'database' => env('DB_DATABASE', 'laravel_db'),
    'username' => env('DB_USERNAME', 'username'),
    'password' => env('DB_PASSWORD', '32425356353'),
    'unix_socket' => env('DB_SOCKET', ''),
    'charset' => 'utf8mb4',
    'collation' => 'utf8mb4_unicode_ci',
    'prefix' => '',
    'strict' => true,
    'engine' => null,

By continuing to use the site, you agree to the use of cookies.