5

I have the following error. Someone is understanding why?

php artisan migrate

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

create_users_table.php

Schema::create('users', function (Blueprint $table) {
    $table->increments('id');
    $table->string('name',255);
    $table->string('email',255)->unique();
    $table->string('password',255);
    $table->rememberToken();
    $table->timestamps();
});
Maytham Fahmi
  • 31,138
  • 14
  • 118
  • 137
ercvs
  • 337
  • 1
  • 5
  • 13
  • 1
    It's because of character set in use with `email` field. 1 character will not be 1 byte, it's *probably* 4 bytes. When you try to make that field unique, it fails since the column is too long for indexing. The way this problem is solved is by creating another column that contains a **hash** of the `email`. You can make that column `email_hash binary(20)` and then save raw `sha1` hash of the email there and make it unique. That makes your index 20 bytes in length, always, and works for your use case. – N.B. Jul 08 '17 at 10:20

3 Answers3

5

you have to do is edit your AppServiceProvider.php on App\Providers\AppServiceProvider file and inside the boot method set a default string length:

use Illuminate\Support\Facades\Schema;

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

Then drop the database manually then composer dump-autoload and php artisan migrate

Leo
  • 7,274
  • 5
  • 26
  • 48
1

Edit AppServiceProvider.php file, you will find this file in app/Providers/AppServiceProvider.php

use Illuminate\Support\Facades\Schema;

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

Then run

composer update

on your terminal. Then try migrating your script, It would solve your problem.

Maytham Fahmi
  • 31,138
  • 14
  • 118
  • 137
S.M Talha
  • 59
  • 1
  • 10
  • use Illuminate\Support\Facades\Schema; public function boot() { Schema::defaultStringLength(191); } php artisan cache:clear // It is must – Subroto Biswas Feb 05 '22 at 04:52
1

Thanks all message

Resolved with next code:

 in config/database.php in mysql section


'charset' => 'utf8mb4',
'collation' => 'utf8mb4_unicode_ci',
 and replace them with with

'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
ercvs
  • 337
  • 1
  • 5
  • 13
  • Now the error message actually makes a lot of sense. I overlooked this setting. I had created my database manually, and indeed I used collation "utf8_unicode_ci". – bvdb Nov 09 '18 at 16:06