Skip to content

[5.4] SQL error when migrating tables #17508

Description

@Demers94
  • Laravel Version: 5.4.0
  • PHP Version: 7.0.12
  • Database Driver & Version: MySQL 5.6.33

Description:

When I create a new 5.4 project and try to migrate the database tables, I get this SQL error :

[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 users add unique users_email_unique(email))

I get this error when running php artisan migrate on a fresh install on a Macbook, on my Windows computer I get the same error except it says that the max length is 1000 bytes instead of 767 bytes.

Steps To Reproduce:

  • Create a new project (laravel new project, with installer 1.3.3)
  • cd into the project
  • Fill in the database information in the .env file
  • Run php artisan migrate

Activity

  1. devcircus commented on Jan 24, 2017

    @devcircus
    Contributor

    In your appserviceprovider boot method, try adding

    Schema::defaultStringLength(191);
    

    Best sure to import Illuminate\Support\Facades\Schema at the top of the service provider.
    There's a note about this in the 5.4 documentation. It's possible this is what is causing your problems.

  2. Demers94 commented on Jan 24, 2017

    @Demers94
    Author

    Thank you @devcircus , adding this line fixed my issue.

    It should be noted however that the problem occurs on my Windows computer (if I don't add the extra line of code in the boot() method) despite running MySQL 5.7.14 on that computer. The documentation says that there could be an issue with versions before 5.7.7, but I'm having a problem with a newer version as well.

  3. i-bajrai commented on Jan 26, 2017

    @i-bajrai
    Contributor

    Why is this closed? The issue is still there? Using homestead I still get this error.

  4. devcircus commented on Jan 26, 2017

    @devcircus
    Contributor

    Check the 5.4 docs in the database / migration section. It's been covered several times in the last few days here, on slack and on the laracasts forum as well.

  5. fernandobandeira commented on Jan 26, 2017

    @fernandobandeira
    Contributor

    If you are on Mysql < 5.7 or MariaDB < 10.2 then enable innodb_large_prefix this will let you have 255 fields on your database you won't need to touch any code.

    On these other versions you don't need, it works out of the box.

  6. pedzed commented on Jan 28, 2017

    @pedzed

    I got this error too with MySQL 5.7.11.

    As @devcircus said, the workaround on https://laravel.com/docs/5.4/migrations#indexes works.

    UPDATE

    According to @rbkkm, to fix this issue, you can decrease the index rather than the field size:

    This lets you use the full 255 characters at the "expense" of index length, rather than getting the full index length at the expense of the varchar field length.

    What @rbkkm seems to be suggesting is this:

    $table->index([DB::raw('email(191)')]);
    $table->unique([DB::raw('email(191)')]);

    So for example, the migration of password_resets's up() method would look like this:

    Schema::create('password_resets', function (Blueprint $table) {
        $table->string('email');
        $table->string('token');
        $table->timestamp('created_at')->nullable();
    
        $table->unique([DB::raw('email(191)')]);
    });

    And for the migration of users:

    Schema::create('users', function (Blueprint $table) {
        $table->increments('id');
        $table->string('name');
        $table->string('email');
        $table->string('password');
        $table->rememberToken();
        $table->timestamps();
    
        $table->index([DB::raw('email(191)')]);
    });
  7. BeRoots commented on Jan 30, 2017

    @BeRoots

    @devcircus : why using 191 ?

  8. ChristopherDosin commented on Feb 4, 2017

    @ChristopherDosin

    Got this Error too with Laravel 5.4.9, Spark 4.0, Valet v2.0.3 & 10.1.16-MariaDB Homebrew.
    Adding Schema::defaultStringLength(191); in the AppServiceprovider boot Method worked for me in this Case.

  9. htxuankhoa commented on Feb 6, 2017

    @htxuankhoa

    @devcircus Thank you!!!

  10. kirgy commented on Feb 10, 2017

    @kirgy

    Should this not be considered an open problem? I understand that it's a documented problem, but shouldn't we expect some level of backwards compatibility with homestead? My homestead version is almost a year old and a new deploy caused this problem for me. The above solution solved it for me.

  11. brandonsimpson commented on Feb 16, 2017

    @brandonsimpson

    Just had a fresh install, still getting this problem. Adding the Schema::defaultStringLength(191); that @devcircus was the trick.

  12. adenijiayocharles commented on Feb 17, 2017

    @adenijiayocharles

    Thanks @devcircus your solution solved my problem.

  13. pedzed commented on Feb 17, 2017

    @pedzed

    @devcircus Thank you!!!

    Thanks @devcircus your solution solved my problem.

    Please, guys. Do not post comments if it does not add anything of value to the issue thread. Every subscriber to the issue gets a useless email. Show your thanks by using the 👍 emoji like the others did.

  14. snapey commented on Feb 18, 2017

    @snapey

    I added to the migration itself

            Schema::defaultStringLength(191);
            Schema::create('users', function (Blueprint $table) {
                $table->increments('id');
                $table->string('name');
                $table->string('email')->unique();
                $table->string('password');
                $table->rememberToken();
                $table->timestamps();
            });
    

    yes, I know I need to consider it on every migration but I would rather that than have it tucked away in some completely unrelated service provider

  15. 66 remaining items

  16. YayaDy commented on May 25, 2018

    @YayaDy

    Please add
    use Illuminate\Support\Facades\Schema;
    boot(){
    Schema::defaultStringLength(191);
    }
    to your app/provider/AppServiceProvider.php

  17. kieuquangloc commented on May 25, 2018

    @kieuquangloc
  18. JensHH commented on Jun 20, 2018

    @JensHH

    Still have the same problem with a fresh installation. Diffrence is, max key length is 1000 bytes instead of 767 bytes.
    SQLSTATE[42000]: Syntax error or access violation: 1071 Specified key was too long; max key length is 1000 bytes (SQL: alter table ltm_translations add unique ixk_ltm_translations_locale_group_key(locale, group, key))

    mysql is 5.7.21, Laravel Framework 5.5.35
    Content of AppServiceProvider.php is:
    `namespace App\Providers;

    use Auth;
    use Carbon\Carbon;
    use Illuminate\Support\ServiceProvider;
    use Illuminate\Support\Facades\Schema;

    class AppServiceProvider extends ServiceProvider
    {
    /**
    * Bootstrap any application services.
    *
    * @return void
    */
    public function boot()
    {
    Schema::defaultStringLength(191);
    // set correct locale for Carbon
    Carbon::setLocale(config('app.locale'));
    }

    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        //
    }
    

    }
    `

  19. FaizanNoor commented on Jul 3, 2018

    @FaizanNoor

    File: config/database.php
    change the following
    FROM ->
    'charset' => 'utf8mb4',
    'collation' => 'utf8mb4_unicode_ci',

    TO ->
    'charset' => 'utf8',
    'collation' => 'utf8_unicode_ci',

  20. SantinoVega commented on Jul 10, 2018

    @SantinoVega

    Hi there. I hope can understandme.
    I solved to follow this steps. in laravel-project/databases/migrations
    edit both files (create_users_table, create_password_reset_table) in function up().
    like this:

    public function up()
        {
            Schema::create('users', function (Blueprint $table) {
                $table->increments('id');
                $table->string('name');
                $table->string('email');
                $table->string('password');
                $table->rememberToken();
                $table->timestamps();
    
                $table->index([DB::raw('email(191)')]);
            });
        }
    

    Tested on:
    Ubuntu 16.04
    10.1.13-MariaDB
    PHP 7.2.7-1

  21. Aryan2500 commented on Jul 15, 2018

    @Aryan2500

    In your appserviceprovider boot method, try adding

    Schema::defaultStringLength(191);

    Dont Forget to copy paste " Illuminate\Support\Facades\Schema; " at the top of the service provider.

  22. pedzed commented on Jul 19, 2018

    @pedzed

    @themsaid This issue thread does not get any more useful comments. People are just repeating things. I suggest closing and locking it.

    P.S. I still find it unreasonable not to mention this more thoroughly in the documentation as I proposed here: laravel/docs#4075.

    To summarize, I think the best solution is provided by @rbkkm, which I explained way up (in this thread): #17508 (comment).


    According to @rbkkm, to fix this issue you can decrease the index rather than the field size:

    This lets you use the full 255 characters at the "expense" of index length, rather than getting the full index length at the expense of the varchar field length.

    What @rbkkm seems to be suggesting is this:

    $table->index([DB::raw('email(191)')]);
    $table->unique([DB::raw('email(191)')]);

    So for example, the migration of password_resets's up() method would look like this:

    Schema::create('password_resets', function (Blueprint $table) {
        $table->string('email');
        $table->string('token');
        $table->timestamp('created_at')->nullable();
    
        $table->unique([DB::raw('email(191)')]);
    });

    And for the migration of users:

    Schema::create('users', function (Blueprint $table) {
        $table->increments('id');
        $table->string('name');
        $table->string('email');
        $table->string('password');
        $table->rememberToken();
        $table->timestamps();
    
        $table->index([DB::raw('email(191)')]);
    });
  23. san-cyclops commented on Aug 14, 2018

    @san-cyclops
  24. udhavsarvaiya commented on Oct 17, 2018

    @udhavsarvaiya

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

        use Illuminate\Support\Facades\Schema;
        
        public function boot()
        {
            Schema::defaultStringLength(191);
        }
    
    

    first you have to delete (if you have) users table, password_resets table from the database and delete users and password_resets entries from migrations table.

    To run all of your outstanding migrations, execute the migrate Artisan command:

    php artisan migrate

  25. Adnan-Jabbar commented on Nov 4, 2018

    @Adnan-Jabbar

    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 users add unique users_email_unique(email))

    Answer:
    Dir:
    App/Providers/AppServiceProvider.php

    Add line in Top:
    use Illuminate\Support\Facades\Schema;

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

  26. royalabhi17 commented on Dec 30, 2018

    @royalabhi17
    • Laravel Version: 5.4.0
    • PHP Version: 7.0.12
    • Database Driver & Version: MySQL 5.6.33

    Description:

    When I create a new 5.4 project and try to migrate the database tables, I get this SQL error :

    [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 users add unique users_email_unique(email))

    I get this error when running php artisan migrate on a fresh install on a Macbook, on my Windows computer I get the same error except it says that the max length is 1000 bytes instead of 767 bytes.

    Steps To Reproduce:

    • Create a new project (laravel new project, with installer 1.3.3)
    • cd into the project
    • Fill in the database information in the .env file
    • Run php artisan migrate

    This issue is still there with Laravel 5.7.17.
    Why this issue is not solved with an update.

  27. devcircus commented on Dec 30, 2018

    @devcircus
    Contributor

    Search the issues. This has been discussed many times.

  28. ArmCM commented on Mar 2, 2019

    @ArmCM

    Laravel 5.7 - define length in email

        public function up()
        {
            Schema::create('users', function (Blueprint $table) {
                $table->increments('id');
                $table->string('name');
                $table->string('email', 191)->unique();
                $table->timestamp('email_verified_at')->nullable();
                $table->string('password');
                $table->rememberToken();
                $table->timestamps();
            });
        }
  29. driesvints commented on Mar 4, 2019

    @driesvints
    Member

    I'm locking this issue because it either has gone off-topic, become a dumping ground for things which shouldn't be in an issue tracker or is just too old.

  30. locked and limited conversation to collaborators on Mar 4, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions