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

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.


Software Engineer | Ethical Hacker & Cybersecurity...

Md Obydullah is a software engineer and full stack developer specialist at Laravel, Django, Vue.js, Node.js, Android, Linux Server, and Ethichal Hacking.

Similar Stories