0
votes

I got this issue when I use laravel migration to create a table in the database. I don't know what might be wrong with it as I use the same command on my previous system. This is the error I got while using composer to create the table.

$ php artisan migrate Migration table created successfully.

[Illuminate\Database\QueryException] SQLSTATE[42000]: Syntax error or access violation: 1071 Specified key was t oo 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 t oo long; max key length is 767 bytes

3

3 Answers

4
votes

Laravel 5.4 uses utf8mb4 by default. One way to fix this error, is to default back to utf8.

Go to your config\database.php and change the database charset to uft8 and the collation to utf8_unicode_ci:

'mysql' => [
    //..
    'charset' => 'utf8',
    'collation' => 'utf8_unicode_ci',
    //..
],
2
votes

The character limit depends on the character set you use. Laravel is using utf8mb4 for which the character limit of the largest index is 191.

You just need to set your character limit to correct one. Read this from Laravel Index Length

Index Lengths & MySQL / MariaDB

Laravel uses the utf8mb4 character set by default, which includes support for storing "emojis" in the database. If you are running a version of MySQL older than the 5.7.7 release or MariaDB older than the 10.2.2 release, you may need to manually configure the default string length generated by migrations in order for MySQL to create indexes for them. You may configure this by calling the Schema::defaultStringLengthmethod within your AppServiceProvider:

use Illuminate\Support\Facades\Schema;

/**
 * Bootstrap any application services.
 *
 * @return void
 */
public function boot()
{
    Schema::defaultStringLength(191);
}

Alternatively, you may enable the innodb_large_prefix option for your database. Refer to your database's documentation for instructions on how to properly enable this option.

1
votes

It's a bug in Laravel 5.4

To fix it, place this above the Schema::create method call:

Schema::defaultStringLength(191);

Read more here:

https://github.com/laravel/framework/issues/17508