When you're using Laravel migrations have you ever come across the error 1071 Specified key was too long; max key length is 767 bytes
. There was a change in Laravel 5.4 that changed the default database character set to utf8mb4, this change allows us to support the storing of emojis. You'll get this error if you have a new application and are running on MySQL v5.7.7 or lower. When you run the first MySQL migration scripts you'll get the following error on the users table on the email column.
[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
The fix for this error is found in the Laravel documentation in the migrations section. You need to change the default string length inside the AppServiceProvider
by using the Schema::defaultStringLength
method.
namespace App\Providers;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\ServiceProvider;
class AppServiceProvider extends ServiceProvider
{
/**
* Bootstrap any application services.
*
* @return void
*/
public function boot()
{
//
Schema::defaultStringLength(191);
}
/**
* Register any application services.
*
* @return void
*/
public function register()
{
//
}
}
Now you'll be able to rerun your migrations and everything will work correctly. An alternative solution is to enable innodb_large_prefix
on your database.