6

I'm trying for migrate a laravel migration but i had an error :

Migrating: 2014_10_12_100000_create_password_resets_table

   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 `password_
resets` add index `password_resets_email_index`(`email`))

my code is :

if (!Schema::hasTable('password_resets')) {
            Schema::create('password_resets', function (Blueprint $table) {
                $table->string('email')->index();
                $table->string('token');
                $table->timestamp('created_at')->nullable();
            });
        }
Artin Zareie
  • 160
  • 3
  • 14

2 Answers2

6

You can set String Length manually by putting this

$table->string('name', 191); // You can put any number in exchange of 191

else

Put This in APP -> Providers -> AppServiceProvider

use Illuminate\Support\Facades\Schema;

public function boot() 
{
    Schema::defaultStringLength(191);
}
Ashish
  • 6,791
  • 3
  • 26
  • 48
  • 1
    I've done some research and found different views. This problem arises because of the use of indexing "unique" in the email field in the users table. So simply adding a limit value of 250 can solve the problem. This value is added to the file migration which creates the users table on the line with the code "unique ()" so it looks like this: $table->string('email', 250)->unique (); – Danang Ponorogo Aug 16 '20 at 04:57
  • This is an ugly hack, only appropriate for legacy Laravel projects that need to be fixed in production yesterday. It will create problems down the road. The correct solution is to upgrade to a recent version of MySQL and/or fix the DB configuration to support the utf8mb4 character set that Laravel uses. – Andrew Koster Oct 01 '20 at 04:21
  • @AndrewKoster if you read the answer date you will get to know that the version available at that time was laravel 5.6 as latest – Ashish Oct 01 '20 at 04:39
  • worked in laravel 8.0 – Shashank Shah Dec 01 '20 at 18:02
0

You should set the default string length to 191 in the boot method of the AppServiceProvider

use Illuminate\Support\Facades\Schema;

public function boot() 
{
    Schema::defaultStringLength(191); 
}
Sujan Gainju
  • 4,273
  • 2
  • 14
  • 34