[solved]Laravel – SQLSTATE[42000]: Syntax error or access violation: 1071 Specified key was too long; max key length is 767 bytes Error

In laravel, you may have encountered an error of ‘specified key was too long‘ frequently after running the php artisan migrate command.

Table of Contents

Error : 

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

Solution :

To solve this error just add Schema::defaultStringLength(191); inside boot() of AppServiceProvider.php as follows.

Don’t forget to add use Illuminate\Support\Facades\Schema;

app\Providers\AppServiceProvider.php

<?php

namespace App\Providers;

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

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);
    }
}

After updating AppServiceProvider.php you have to run migrations again. If you encounter ‘SQLSTATE[42S01]: Base table or view already exists: 1050 Table…’ error during running the php artisan migrate command then drop already exists tables in your database and run the command again or you can just run the following command: 

Note: Following command will drop all the tables and create new tables from the migrations.

php artisan migrate:fresh

Hope it will help you.

Leave a Reply

avatar
  Subscribe  
Notify of