“Specified key was too long error” error in Laravel 5.4

I upgraded my Laravel installation to 5.4 and encountered the error below:

 [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

This is actually documented in the official Laravel website here: https://laravel.com/docs/master/migrations#creating-indexes where it fixes the issue. You need to call the Schema::defaultStringLength method within your AppServiceProvider class’ boot method.

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

However, the documentation does not mention that you need to declare the Schema class at the top, or else you will encounter the error like below:

                                                         
  [Symfony\Component\Debug\Exception\FatalThrowableError]  
  Class 'App\Providers\Schema' not found

So be sure to add:  use Schema;

<?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use Schema;

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()
    {
        //
    }
}

Adding a backslash before Schema also works fine.

\Schema::defaultStringLength(191);

I hope this somehow helps :)

trizaeron