Bangeee
Bangeee

Reputation: 83

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

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

Upvotes: 8

Views: 17603

Answers (3)

Abdeldjalil Chougui
Abdeldjalil Chougui

Reputation: 815

According to the official Laravel 7.x documentation, you can solve this quite easily.

Update your /app/Providers/AppServiceProvider.php file to contain:

use Illuminate\Support\Facades\Schema;

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

Upvotes: 0

Ali Raza
Ali Raza

Reputation: 720

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

Upvotes: 2

Doh09
Doh09

Reputation: 2385

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.

Upvotes: 15

Related Questions