Md. Obydullah Howdy, I am Md. Obydullah from Bangladesh. I love to write the article which may help others. It's my passion.

How to Fix “Specified key was too long” Error in Laravel

Last modified on July 13, 2019 43 sec read

In Laravel, “Specified key was too long” error is a common error. It occurs for migration. The error looks like:

[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))

In the new project when we try to migrate the project, most of the times we have to see this. But we can easily solve this issue by adding defaultStringLength() of Schema in AppServiceProvider.php.

Solution

Open AppServiceProvider.php from app>Providers. We need to add two lines to the file. We have to include the Schema use Illuminate\Support\Facades\Schema; and need to add this line Schema::defaultStringLength(191); in the boot() method.

I’ve added those two lines and the AppServiceProvider.php looks like:

AppServiceProvider.php
<?php

namespace App\Providers;

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

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

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

You can also copy and paste this code to your project file. Now run the migration. It should work as normal.

We have solved the problem. 🙂

Md. Obydullah Howdy, I am Md. Obydullah from Bangladesh. I love to write the article which may help others. It's my passion.

Leave a Reply

Your email address will not be published. Required fields are marked *