Fixing "Specified key was too long error" exception in Laravel 5.4

Fixing "Specified key was too long error" exception in Laravel 5.4

Since Laravel 5.4, there were a little change on the default database character set. Now the default charset used is utf8mb4 that includes support for Emojis. This issue affects exclusivelz new applications and as long as you are running MySQL >= v5.7.7, you won't need to do anything. This error appears usually on MariaDB or older versions of MySQL, triggered specifically during migrations:

[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 doesn't rely on the tool itself (MariaDB) but on your code. To prevent this exception, as mentioned on the official migration guide of Laravel, you only need to specify the default length of the strings in your AppServiceProvider simply importing the Schema class and running the static method defaultStringLength from the class on the boot function:

use Illuminate\Support\Facades\Schema;

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

For example, in default projects you will find this file in /yourapp/app/Providers/AppServiceProvider.php and after the changes the file should look something like:

<?php

// . yourapp\app\Providers\AppServiceProvider.php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;

// 1. Import Schema
use Illuminate\Support\Facades\Schema;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        // 2. Set default string length
        Schema::defaultStringLength(191);
    }

    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        //
    }
}

If you run the migrations once more, the exception shouldn't appear anymore.

Happy coding !

This could interest you

Become a more social person