5
votes

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

2
Yes, anyone can easily find that link with Google. The problem is that the link is explaining an ugly workaround for legacy code. When you run into this error with an up-to-date Laravel project, this link just tells you how to hobble your code to avoid fixing the DB server.Andrew Koster

2 Answers

8
votes

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.

0
votes

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