Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

mysql

laravel

Getting an error after submiting "php artisan migrate:fresh" in cmd.

<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateUsersTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('name');
            $table->string('email')->unique();
            $table->timestamp('email_verified_at')->nullable();
            $table->string('password');
            $table->rememberToken();
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('users');
    }
}

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

like image 263
Bangeee Avatar asked May 25 '19 19:05

Bangeee


2 Answers

From this link: https://laravel-news.com/laravel-5-4-key-too-long-error

For those running MariaDB or older versions of MySQL you may hit this error when trying to run migrations

As outlined in the Migrations guide to fix this all you have to do is edit your AppServiceProvider.php file and inside the boot method set a default string length:

use Illuminate\Support\Facades\Schema;

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

After that everything should work as normal.

Please note that as per Andrew Koster's comment below it's possible this is only a solution intended for legacy code. You may wish to look into different solutions for up-to-date projects.

like image 98
Doh09 Avatar answered Nov 15 '22 09:11

Doh09


EDIT: FYI ... v4 of this package, which adds some unique indexes in the migration, requires 125 instead of 191 if you're using MySQL 8.0. (MariaDB doesn't require any of this).

like image 34
Ali Raza Avatar answered Nov 15 '22 08:11

Ali Raza