Laravel 5.4 Specified key was too long

I installed a new Laravel 5.4 project, then tried to run the already existing migrations (without changing anything besides my DB name and user & password). I got the following errors:

[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

After some research (which I've should be done before creating my new project) I've found out that Laravel 5.4 uses the utf8mb4 character set by default, which includes support for storing "emojis" in the DB. This affect you, if you use MySQL prior to v5.7.7 or MariaDB prior to v10.2.2. (I use MariadDB v10.1.14)

You have some options to resolve this issue.

  • You could update your MySQL/MariaDB

... but if you don't want to do it right now, you have some other options too:

  • Use utf8mb4, by adding one line of code to the boot() method in App\Providers\AppServiceProvider.php:
<?php

namespace App\Providers;

use Illuminate\Support\Facades\Schema;  
use Illuminate\Support\ServiceProvider;

class AppServiceProvider extends ServiceProvider  
{
    public function boot()
    {
        Schema::defaultStringLength(191);
    }

    public function register()
    {
        //
    }
}
  • or you could use utf8 further on. All you need to do is edit two lines in your database config file (config/database.php). Find the mysql config, and do this changes:

old config

'charset' => 'utf8mb4',  
'collation' => 'utf8mb4_unicode_ci',  

new config

'charset' => 'utf8',  
'collation' => 'utf8_unicode_ci',  

Hope it helped you :) Any suggestions are welcome.