February 13, 2023

How to Fix the "Specified Key Was Too Long" Error in Laravel (3 Solutions)

Photo of Marco Orta Marco Orta | 2 min read
Compartir
MySQL "Specified key was too long" error message in the Laravel console during migrations

⚙️ 2026 Note: if you are using MySQL 8 or MariaDB 10.5+ with Laravel 9 or later, you should no longer see this error on new projects: the default charset is utf8mb4 with innodb_default_row_format=DYNAMIC, and indexes now support up to 3072 bytes. This article is still useful if you are working with legacy databases, older servers, or shared hosting environments still running MySQL 5.6/5.7 or MariaDB 10.1.

How many times have you installed a new Laravel project only to run your migrations and be greeted with an error in the console:

[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_unique(email))

[PDOException]
SQLSTATE[42000]: Syntax error or access violation: 1071 Specified key was too long; max key length is 767 bytes

There are 3 ways to fix it:

Solution 1

If you are using MariaDB or a version of MySQL older than v5.7.7, simply upgrade to the latest stable release and you will never see this problem again.

Solution 2

If you cannot or do not want to upgrade MySQL, try modifying the MySQL engine in the config/database.php file:

'mysql' => [
    ...
    'engine' => 'InnoDB',
]

Solution 3

If Solution 2 does not work for some reason, add the following line to app/Providers/AppServiceProvider.php:

use Illuminate\Support\Facades\Schema;

public function boot()
{
    Schema::defaultStringLength(191);
}

Why does this error occur?

Starting with Laravel 5.4, the default database character set was changed to utf8mb4, which includes support for storing emojis. This only affects applications running on versions of MySQL older than v5.7.7.

Compartir

Search

Tags