Laravel syntax error or access violation 1071 specified key was too long

Migration error on Laravel 5.4 with php artisan make:auth [IlluminateDatabaseQueryException] SQLS...

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

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

use IlluminateSupportFacadesSchema;

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

Alternatively, you may enable the innodb_large_prefix option for your database. Refer to your database’s documentation for instructions on how to properly enable this option.

Ryan's user avatar

Ryan

21.5k29 gold badges172 silver badges343 bronze badges

answered Feb 15, 2017 at 9:52

abSiddique's user avatar

abSiddiqueabSiddique

11.1k3 gold badges23 silver badges30 bronze badges

10

I don’t know why the above solution and the official solution which is adding

Schema::defaultStringLength(191);

in AppServiceProvider didn’t work for me.
What worked for was editing the database.php file in config folder.
Just edit

'charset' => 'utf8mb4',
'collation' => 'utf8mb4_unicode_ci',

to

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

and it should work, although you will be unable to store extended multibyte characters like emoji.

This is an ugly hack and don’t do if you want to store string in non english language, emoji

I did it with Laravel 5.7.

Don’t forget to stop and launch again the server.

user's user avatar

user

4,9056 gold badges17 silver badges35 bronze badges

answered Sep 17, 2017 at 8:29

Koushik Das's user avatar

Koushik DasKoushik Das

8,8923 gold badges47 silver badges45 bronze badges

8

I’m just adding this answer here as it’s the quickest solution for me. Just set the default database engine to 'InnoDB' on

/config/database.php

'mysql' => [
    ...,
    ...,
    'engine' => 'InnoDB',
 ]

then run php artisan config:cache to clear and refresh the configuration cache

EDIT:
Answers found here might explain what’s behind the scenes of this one

answered Oct 9, 2017 at 7:50

Dexter Bengil's user avatar

Dexter BengilDexter Bengil

5,6856 gold badges36 silver badges53 bronze badges

6

Laravel 7.X (also works in 8X): Simple Solution.

Option-1:

php artisan db:wipe 

Update these values(Below) of mysql array in /config/database.php

'charset' => 'utf8',
'collation' => 'utf8_general_ci',

And then

php artisan migrate

It’s Done! Migration Tables will be created successfully.


Option-2:

Use php artisan db:wipe or delete/drop all the tables of your database manually.

Update your AppServiceProvider.php [ Located in app/Providers/AppServiceProvider.php ]

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

And then

php artisan migrate

It’s Done!

Pitfall: I would like to mention of @shock_gone_wild ‘s comment

Be careful about this solution (Option-2). If you index email fields for example,
stored emails can only have a max length of 191 chars. This is less
than the official RFC states.


Optionally I Tried out these possible ways (like below) but doesn’t work.

php artisan config:cache php artisan migrate:fresh

php artisan migrate:reset

answered Jan 7, 2021 at 8:47

perfectionist1's user avatar

perfectionist1perfectionist1

7272 gold badges9 silver badges14 bronze badges

0

This issue is caused in Laravel 5.4 by the database version.

According to the docs (in the Index Lengths & MySQL / MariaDB section):

Laravel uses the utf8mb4 character set by default, which includes
support for storing «emojis» in the database. If you are running a
version of MySQL older than the 5.7.7 release or MariaDB older than
the 10.2.2 release, you may need to manually configure the default
string length generated by migrations in order for MySQL to create
indexes for them. You may configure this by calling the
Schema::defaultStringLength method within your AppServiceProvider.

In other words, in <ROOT>/app/Providers/AppServiceProvider.php:

// Import Schema
use IlluminateSupportFacadesSchema;
// ...

class AppServiceProvider extends ServiceProvider
{

public function boot()
{
    // Add the following line
    Schema::defaultStringLength(191);
}

// ...

}

But as the comment on the other answer says:

Be careful about this solution. If you index email fields for example,
stored emails can only have a max length of 191 chars. This is less
than the official RFC states.

So the documentation also proposes another solution:

Alternatively, you may enable the innodb_large_prefix option for your
database. Refer to your database’s documentation for instructions on
how to properly enable this option.

answered Feb 20, 2017 at 19:39

Esteban Herrera's user avatar

Esteban HerreraEsteban Herrera

2,1882 gold badges22 silver badges31 bronze badges

For someone who don’t want to change AppServiceProvider.php.
(In my opinion, it’s bad idea to change AppServiceProvider.php just for migration)

You can add back the data length to the migration file under database/migrations/ as below:

create_users_table.php

$table->string('name',64);
$table->string('email',128)->unique();

create_password_resets_table.php

$table->string('email',128)->index();

Dexter Bengil's user avatar

answered Apr 21, 2017 at 16:46

helloroy's user avatar

helloroyhelloroy

3772 silver badges6 bronze badges

2

I have solved this issue and edited my config->database.php file to like my database ('charset'=>'utf8') and the ('collation'=>'utf8_general_ci'), so my problem is solved the code as follow:

'mysql' => [
        'driver' => 'mysql',
        'host' => env('DB_HOST', '127.0.0.1'),
        'port' => env('DB_PORT', '3306'),
        'database' => env('DB_DATABASE', 'forge'),
        'username' => env('DB_USERNAME', 'forge'),
        'password' => env('DB_PASSWORD', ''),
        'unix_socket' => env('DB_SOCKET', ''),
        'charset' => 'utf8',
        'collation' => 'utf8_general_ci',
        'prefix' => '',
        'strict' => true,
        'engine' => null,
    ],

Dexter Bengil's user avatar

answered Apr 20, 2018 at 6:24

Ahmad Shakib's user avatar

1

works like charm for me!

Add this to config/database.php

'engine' => 'InnoDB ROW_FORMAT=DYNAMIC',

instead of

'engine' => 'null',

answered Jan 22, 2021 at 2:39

Alaa ElAlfi's user avatar

2

I am adding two sollution that work for me.

1st sollution is:

  1. Open database.php file insde config dir/folder.
  2. Edit 'engine' => null, to 'engine' => 'InnoDB',

    This worked for me.

2nd sollution is:

  1. Open database.php file insde config dir/folder.
    2.Edit
    'charset' => 'utf8mb4',
    'collation' => 'utf8mb4_unicode_ci',


    to

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

Goodluck

answered Jun 28, 2018 at 13:33

Arslan Ahmad khan's user avatar

0

1- Go to /config/database.php and find these lines

'mysql' => [
    ...,
    'charset' => 'utf8mb4',
    'collation' => 'utf8mb4_unicode_ci',
    ...,
    'engine' => null,
 ]

and change them to:

'mysql' => [
    ...,
    'charset' => 'utf8',
    'collation' => 'utf8_unicode_ci',
    ...,
    'engine' => 'InnoDB',
 ]

2- Run php artisan config:cache to reconfigure laravel

3- Delete the existing tables in your database and then run php artisan migrate again

answered Feb 8, 2019 at 8:10

mohammad asghari's user avatar

mohammad asgharimohammad asghari

1,7041 gold badge16 silver badges23 bronze badges

2

Open this file here: /app/Providers/AppServiceProvider.php

And Update this code as my image:

use IlluminateSupportFacadesSchema;

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

enter image description here

answered Apr 16, 2022 at 5:05

Amranur Rahman's user avatar

1

I have found two solutions for this error

OPTION 1:

Open your user and password_reset table in database/migrations folder

And just change the length of the email:

$table->string('email',191)->unique();

OPTION 2:

Open your app/Providers/AppServiceProvider.php file and inside the boot() method set a default string length:

use IlluminateSupportFacadesSchema;

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

answered Feb 8, 2018 at 6:37

Udhav Sarvaiya's user avatar

Udhav SarvaiyaUdhav Sarvaiya

9,03812 gold badges55 silver badges62 bronze badges

The solution no one tells is that in Mysql v5.5 and later InnoDB is the default storage engine which does not have this problem but in many cases like mine there are some old mysql ini configuration files which are using old MYISAM storage engine like below.

default-storage-engine=MYISAM

which is creating all these problems and the solution is to change default-storage-engine to InnoDB in the Mysql’s ini configuration file once and for all instead of doing temporary hacks.

default-storage-engine=InnoDB

And if you are on MySql v5.5 or later then InnoDB is the default engine so you do not need to set it explicitly like above, just remove the default-storage-engine=MYISAM if it exist from your ini file and you are good to go.

answered Nov 8, 2019 at 20:06

Ali A. Dhillon's user avatar

3

Instead of setting a limit on length I would propose the following, which has worked for me.

Inside:

config/database.php

replace this line for mysql:

'engine' => 'InnoDB ROW_FORMAT=DYNAMIC',

with:

'engine' => null,

GuruBob's user avatar

GuruBob

8431 gold badge10 silver badges21 bronze badges

answered Jul 24, 2017 at 20:21

Md. Noor-A-Alam Siddique's user avatar

in database.php

-add this line:

‘engine’ => ‘InnoDB ROW_FORMAT=DYNAMIC’,

enter image description here

answered May 4, 2022 at 3:42

Mizael Clistion's user avatar

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 IlluminateSupportFacadesSchema;

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

Note: 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

After that everything should work as normal.

Dexter Bengil's user avatar

answered Jan 19, 2018 at 5:43

As already specified we add to the AppServiceProvider.php in App/Providers

use IlluminateSupportFacadesSchema;  // add this

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

you can see more details in the link bellow (search for «Index Lengths & MySQL / MariaDB»)
https://laravel.com/docs/5.5/migrations

BUT WELL THAT’s not what I published all about! the thing is even when doing the above you will likely to get another error (that’s when you run php artisan migrate command and because of the problem of the length, the operation will likely stuck in the middle. solution is below, and the user table is likely created without the rest or not totally correctly)
we need to roll back. the default roll back will not work. because the operation of migration didn’t like finish. you need to delete the new created tables in the database manually.

we can do it using tinker as in below:

L:todos> php artisan tinker

Psy Shell v0.8.15 (PHP 7.1.10 — cli) by Justin Hileman

>>> Schema::drop('users')

=> null

I myself had a problem with users table.

after that you’re good to go

php artisan migrate:rollback

php artisan migrate

Dexter Bengil's user avatar

answered Jan 17, 2018 at 20:37

Mohamed Allal's user avatar

Mohamed AllalMohamed Allal

16.2k4 gold badges87 silver badges91 bronze badges

In laravel 9

First set the default database engine to InnoDB on

/config/database.php

'engine' => 'InnoDB',

then run php artisan config:cache to clear and refresh the configuration cache.

php artisan db:wipe

Change these values of mysql array in /config/database.php as follows
'charset' => 'utf8', 'collation' => 'utf8_general_ci',
Then

php artisan migrate
That’s all! Migration Tables will be created successfully.

answered Sep 12, 2022 at 7:21

Developer Sam's user avatar

1

If you want to change in AppServiceProvider then you need to define the length of email field in migration. just replace the first line of code to the second line.

create_users_table

$table->string('email')->unique();
$table->string('email', 50)->unique();

create_password_resets_table

$table->string('email')->index();
$table->string('email', 50)->index();

After successfully changes you can run the migration.
Note: first you have to delete (if you have) users table, password_resets table from the database and delete users and password_resets entries from migration table.

answered Jun 25, 2017 at 8:03

Chintan Kotadiya's user avatar

Chintan KotadiyaChintan Kotadiya

1,3281 gold badge11 silver badges19 bronze badges

Schema::defaultStringLength(191); will define the length of all strings 191 by default which may ruin your database. You must not go this way.

Just define the length of any specific column in the database migration class. For example, I’m defining the «name», «username» and «email» in the CreateUsersTable class as below:

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

answered Apr 23, 2018 at 9:08

Fatema Tuz Zuhora's user avatar

0

The recommended solution is to enable innodb_large_prefix option of MySQL so you won’t be getting into subsequent problems. And here is how to do that:

Open the my.ini MySQL configuration file and add the below lines under the [mysqld] line like this.

[mysqld]
innodb_file_format = Barracuda
innodb_large_prefix = 1
innodb_file_per_table = ON

After that, save your changes and restart your MySQL service.

Rollback if you need to and then re-run your migration.


Just in case your problem still persists, go to your database configuration file and set

'engine' => null, to 'engine' => 'innodb row_format=dynamic'

Hope it helps!

answered Nov 28, 2018 at 7:59

Sammie's user avatar

SammieSammie

1,4911 gold badge21 silver badges17 bronze badges

I have just modified following line in users and password_resets migration file.

Old : $table->string('email')->unique();

New : $table->string('email', 128)->unique();

Uddyan Semwal's user avatar

answered Nov 16, 2018 at 18:34

Mahesh Gaikwad's user avatar

This is common since Laravel 5.4 changed the default database charater set to utf8mb4. What you have to do, is: edit your AppProviders.php by putting this code before the class declaration

use IlluminateSupportFacadesSchema;

Also, add this to the ‘boot’ function
Schema::defaultStringLength(191);

answered Feb 8, 2018 at 10:44

Treasure's user avatar

If you don’t have any data assigned already to you database do the following:

  1. Go to app/Providers/AppServiceProvide.php and add

use IlluminateSupportServiceProvider;

and inside of the method boot();

Schema::defaultStringLength(191);

  1. Now delete the records in your database, user table for ex.

  2. run the following

php artisan config:cache

php artisan migrate

Community's user avatar

answered Apr 21, 2019 at 1:41

Levinski Polish's user avatar

1

Try with default string length 125 (for MySQL 8.0).

defaultStringLength(125)

answered May 20, 2021 at 17:45

Ajay's user avatar

AjayAjay

8288 silver badges17 bronze badges

I think to force StringLenght to 191 is a really bad idea.
So I investigate to understand what is going on.

I noticed that this message error :

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

Started to show up after I updated my MySQL version. So I’ve checked the tables with PHPMyAdmin and I’ve noticed that all the new tables created were with the collation utf8mb4_unicode_ci instead of utf8_unicode_ci for the old ones.

In my doctrine config file, I noticed that charset was set to utf8mb4, but all my previous tables were created in utf8, so I guess this is some update magic that it start to work on utf8mb4.

Now the easy fix is to change the line charset in your ORM config file.
Then to drop the tables using utf8mb4_unicode_ci if you are in dev mode or fixe the charset if you can’t drop them.

For Symfony 4

change charset: utf8mb4 to charset: utf8 in config/packages/doctrine.yaml

Now my doctrine migrations are working again just fine.

answered May 17, 2018 at 9:03

Kaizoku Gambare's user avatar

Kaizoku GambareKaizoku Gambare

3,0043 gold badges28 silver badges40 bronze badges

0

first delete all tables of the database in the localhost

Change Laravel default database (utf8mb4) properties in file config/database.php to:

‘charset’ => ‘utf8’,
‘collation’ => ‘utf8_unicode_ci’,

after then
Changing my local database properties utf8_unicode_ci.
php artisan migrate
it is ok.

answered Jul 7, 2019 at 20:59

Goldman.Vahdettin's user avatar

For anyone else who might run into this, my issue was that I was making a column of type string and trying to make it ->unsigned() when I meant for it to be an integer.

answered Apr 25, 2018 at 19:20

Brynn Bateman's user avatar

Brynn BatemanBrynn Bateman

7391 gold badge8 silver badges22 bronze badges

The approached that work here was pass a second param with the key name (a short one):

$table->string('my_field_name')->unique(null,'key_name');

answered Jul 24, 2018 at 13:23

Tiago Gouvêa's user avatar

Tiago GouvêaTiago Gouvêa

14.3k4 gold badges72 silver badges79 bronze badges

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

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

use IlluminateSupportFacadesSchema;

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

Alternatively, you may enable the innodb_large_prefix option for your database. Refer to your database’s documentation for instructions on how to properly enable this option.

Ryan's user avatar

Ryan

21.5k29 gold badges172 silver badges343 bronze badges

answered Feb 15, 2017 at 9:52

abSiddique's user avatar

abSiddiqueabSiddique

11.1k3 gold badges23 silver badges30 bronze badges

10

I don’t know why the above solution and the official solution which is adding

Schema::defaultStringLength(191);

in AppServiceProvider didn’t work for me.
What worked for was editing the database.php file in config folder.
Just edit

'charset' => 'utf8mb4',
'collation' => 'utf8mb4_unicode_ci',

to

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

and it should work, although you will be unable to store extended multibyte characters like emoji.

This is an ugly hack and don’t do if you want to store string in non english language, emoji

I did it with Laravel 5.7.

Don’t forget to stop and launch again the server.

user's user avatar

user

4,9056 gold badges17 silver badges35 bronze badges

answered Sep 17, 2017 at 8:29

Koushik Das's user avatar

Koushik DasKoushik Das

8,8923 gold badges47 silver badges45 bronze badges

8

I’m just adding this answer here as it’s the quickest solution for me. Just set the default database engine to 'InnoDB' on

/config/database.php

'mysql' => [
    ...,
    ...,
    'engine' => 'InnoDB',
 ]

then run php artisan config:cache to clear and refresh the configuration cache

EDIT:
Answers found here might explain what’s behind the scenes of this one

answered Oct 9, 2017 at 7:50

Dexter Bengil's user avatar

Dexter BengilDexter Bengil

5,6856 gold badges36 silver badges53 bronze badges

6

Laravel 7.X (also works in 8X): Simple Solution.

Option-1:

php artisan db:wipe 

Update these values(Below) of mysql array in /config/database.php

'charset' => 'utf8',
'collation' => 'utf8_general_ci',

And then

php artisan migrate

It’s Done! Migration Tables will be created successfully.


Option-2:

Use php artisan db:wipe or delete/drop all the tables of your database manually.

Update your AppServiceProvider.php [ Located in app/Providers/AppServiceProvider.php ]

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

And then

php artisan migrate

It’s Done!

Pitfall: I would like to mention of @shock_gone_wild ‘s comment

Be careful about this solution (Option-2). If you index email fields for example,
stored emails can only have a max length of 191 chars. This is less
than the official RFC states.


Optionally I Tried out these possible ways (like below) but doesn’t work.

php artisan config:cache php artisan migrate:fresh

php artisan migrate:reset

answered Jan 7, 2021 at 8:47

perfectionist1's user avatar

perfectionist1perfectionist1

7272 gold badges9 silver badges14 bronze badges

0

This issue is caused in Laravel 5.4 by the database version.

According to the docs (in the Index Lengths & MySQL / MariaDB section):

Laravel uses the utf8mb4 character set by default, which includes
support for storing «emojis» in the database. If you are running a
version of MySQL older than the 5.7.7 release or MariaDB older than
the 10.2.2 release, you may need to manually configure the default
string length generated by migrations in order for MySQL to create
indexes for them. You may configure this by calling the
Schema::defaultStringLength method within your AppServiceProvider.

In other words, in <ROOT>/app/Providers/AppServiceProvider.php:

// Import Schema
use IlluminateSupportFacadesSchema;
// ...

class AppServiceProvider extends ServiceProvider
{

public function boot()
{
    // Add the following line
    Schema::defaultStringLength(191);
}

// ...

}

But as the comment on the other answer says:

Be careful about this solution. If you index email fields for example,
stored emails can only have a max length of 191 chars. This is less
than the official RFC states.

So the documentation also proposes another solution:

Alternatively, you may enable the innodb_large_prefix option for your
database. Refer to your database’s documentation for instructions on
how to properly enable this option.

answered Feb 20, 2017 at 19:39

Esteban Herrera's user avatar

Esteban HerreraEsteban Herrera

2,1882 gold badges22 silver badges31 bronze badges

For someone who don’t want to change AppServiceProvider.php.
(In my opinion, it’s bad idea to change AppServiceProvider.php just for migration)

You can add back the data length to the migration file under database/migrations/ as below:

create_users_table.php

$table->string('name',64);
$table->string('email',128)->unique();

create_password_resets_table.php

$table->string('email',128)->index();

Dexter Bengil's user avatar

answered Apr 21, 2017 at 16:46

helloroy's user avatar

helloroyhelloroy

3772 silver badges6 bronze badges

2

I have solved this issue and edited my config->database.php file to like my database ('charset'=>'utf8') and the ('collation'=>'utf8_general_ci'), so my problem is solved the code as follow:

'mysql' => [
        'driver' => 'mysql',
        'host' => env('DB_HOST', '127.0.0.1'),
        'port' => env('DB_PORT', '3306'),
        'database' => env('DB_DATABASE', 'forge'),
        'username' => env('DB_USERNAME', 'forge'),
        'password' => env('DB_PASSWORD', ''),
        'unix_socket' => env('DB_SOCKET', ''),
        'charset' => 'utf8',
        'collation' => 'utf8_general_ci',
        'prefix' => '',
        'strict' => true,
        'engine' => null,
    ],

Dexter Bengil's user avatar

answered Apr 20, 2018 at 6:24

Ahmad Shakib's user avatar

1

works like charm for me!

Add this to config/database.php

'engine' => 'InnoDB ROW_FORMAT=DYNAMIC',

instead of

'engine' => 'null',

answered Jan 22, 2021 at 2:39

Alaa ElAlfi's user avatar

2

I am adding two sollution that work for me.

1st sollution is:

  1. Open database.php file insde config dir/folder.
  2. Edit 'engine' => null, to 'engine' => 'InnoDB',

    This worked for me.

2nd sollution is:

  1. Open database.php file insde config dir/folder.
    2.Edit
    'charset' => 'utf8mb4',
    'collation' => 'utf8mb4_unicode_ci',


    to

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

Goodluck

answered Jun 28, 2018 at 13:33

Arslan Ahmad khan's user avatar

0

1- Go to /config/database.php and find these lines

'mysql' => [
    ...,
    'charset' => 'utf8mb4',
    'collation' => 'utf8mb4_unicode_ci',
    ...,
    'engine' => null,
 ]

and change them to:

'mysql' => [
    ...,
    'charset' => 'utf8',
    'collation' => 'utf8_unicode_ci',
    ...,
    'engine' => 'InnoDB',
 ]

2- Run php artisan config:cache to reconfigure laravel

3- Delete the existing tables in your database and then run php artisan migrate again

answered Feb 8, 2019 at 8:10

mohammad asghari's user avatar

mohammad asgharimohammad asghari

1,7041 gold badge16 silver badges23 bronze badges

2

Open this file here: /app/Providers/AppServiceProvider.php

And Update this code as my image:

use IlluminateSupportFacadesSchema;

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

enter image description here

answered Apr 16, 2022 at 5:05

Amranur Rahman's user avatar

1

I have found two solutions for this error

OPTION 1:

Open your user and password_reset table in database/migrations folder

And just change the length of the email:

$table->string('email',191)->unique();

OPTION 2:

Open your app/Providers/AppServiceProvider.php file and inside the boot() method set a default string length:

use IlluminateSupportFacadesSchema;

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

answered Feb 8, 2018 at 6:37

Udhav Sarvaiya's user avatar

Udhav SarvaiyaUdhav Sarvaiya

9,03812 gold badges55 silver badges62 bronze badges

The solution no one tells is that in Mysql v5.5 and later InnoDB is the default storage engine which does not have this problem but in many cases like mine there are some old mysql ini configuration files which are using old MYISAM storage engine like below.

default-storage-engine=MYISAM

which is creating all these problems and the solution is to change default-storage-engine to InnoDB in the Mysql’s ini configuration file once and for all instead of doing temporary hacks.

default-storage-engine=InnoDB

And if you are on MySql v5.5 or later then InnoDB is the default engine so you do not need to set it explicitly like above, just remove the default-storage-engine=MYISAM if it exist from your ini file and you are good to go.

answered Nov 8, 2019 at 20:06

Ali A. Dhillon's user avatar

3

Instead of setting a limit on length I would propose the following, which has worked for me.

Inside:

config/database.php

replace this line for mysql:

'engine' => 'InnoDB ROW_FORMAT=DYNAMIC',

with:

'engine' => null,

GuruBob's user avatar

GuruBob

8431 gold badge10 silver badges21 bronze badges

answered Jul 24, 2017 at 20:21

Md. Noor-A-Alam Siddique's user avatar

in database.php

-add this line:

‘engine’ => ‘InnoDB ROW_FORMAT=DYNAMIC’,

enter image description here

answered May 4, 2022 at 3:42

Mizael Clistion's user avatar

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 IlluminateSupportFacadesSchema;

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

Note: 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

After that everything should work as normal.

Dexter Bengil's user avatar

answered Jan 19, 2018 at 5:43

As already specified we add to the AppServiceProvider.php in App/Providers

use IlluminateSupportFacadesSchema;  // add this

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

you can see more details in the link bellow (search for «Index Lengths & MySQL / MariaDB»)
https://laravel.com/docs/5.5/migrations

BUT WELL THAT’s not what I published all about! the thing is even when doing the above you will likely to get another error (that’s when you run php artisan migrate command and because of the problem of the length, the operation will likely stuck in the middle. solution is below, and the user table is likely created without the rest or not totally correctly)
we need to roll back. the default roll back will not work. because the operation of migration didn’t like finish. you need to delete the new created tables in the database manually.

we can do it using tinker as in below:

L:todos> php artisan tinker

Psy Shell v0.8.15 (PHP 7.1.10 — cli) by Justin Hileman

>>> Schema::drop('users')

=> null

I myself had a problem with users table.

after that you’re good to go

php artisan migrate:rollback

php artisan migrate

Dexter Bengil's user avatar

answered Jan 17, 2018 at 20:37

Mohamed Allal's user avatar

Mohamed AllalMohamed Allal

16.2k4 gold badges87 silver badges91 bronze badges

In laravel 9

First set the default database engine to InnoDB on

/config/database.php

'engine' => 'InnoDB',

then run php artisan config:cache to clear and refresh the configuration cache.

php artisan db:wipe

Change these values of mysql array in /config/database.php as follows
'charset' => 'utf8', 'collation' => 'utf8_general_ci',
Then

php artisan migrate
That’s all! Migration Tables will be created successfully.

answered Sep 12, 2022 at 7:21

Developer Sam's user avatar

1

If you want to change in AppServiceProvider then you need to define the length of email field in migration. just replace the first line of code to the second line.

create_users_table

$table->string('email')->unique();
$table->string('email', 50)->unique();

create_password_resets_table

$table->string('email')->index();
$table->string('email', 50)->index();

After successfully changes you can run the migration.
Note: first you have to delete (if you have) users table, password_resets table from the database and delete users and password_resets entries from migration table.

answered Jun 25, 2017 at 8:03

Chintan Kotadiya's user avatar

Chintan KotadiyaChintan Kotadiya

1,3281 gold badge11 silver badges19 bronze badges

Schema::defaultStringLength(191); will define the length of all strings 191 by default which may ruin your database. You must not go this way.

Just define the length of any specific column in the database migration class. For example, I’m defining the «name», «username» and «email» in the CreateUsersTable class as below:

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

answered Apr 23, 2018 at 9:08

Fatema Tuz Zuhora's user avatar

0

The recommended solution is to enable innodb_large_prefix option of MySQL so you won’t be getting into subsequent problems. And here is how to do that:

Open the my.ini MySQL configuration file and add the below lines under the [mysqld] line like this.

[mysqld]
innodb_file_format = Barracuda
innodb_large_prefix = 1
innodb_file_per_table = ON

After that, save your changes and restart your MySQL service.

Rollback if you need to and then re-run your migration.


Just in case your problem still persists, go to your database configuration file and set

'engine' => null, to 'engine' => 'innodb row_format=dynamic'

Hope it helps!

answered Nov 28, 2018 at 7:59

Sammie's user avatar

SammieSammie

1,4911 gold badge21 silver badges17 bronze badges

I have just modified following line in users and password_resets migration file.

Old : $table->string('email')->unique();

New : $table->string('email', 128)->unique();

Uddyan Semwal's user avatar

answered Nov 16, 2018 at 18:34

Mahesh Gaikwad's user avatar

This is common since Laravel 5.4 changed the default database charater set to utf8mb4. What you have to do, is: edit your AppProviders.php by putting this code before the class declaration

use IlluminateSupportFacadesSchema;

Also, add this to the ‘boot’ function
Schema::defaultStringLength(191);

answered Feb 8, 2018 at 10:44

Treasure's user avatar

If you don’t have any data assigned already to you database do the following:

  1. Go to app/Providers/AppServiceProvide.php and add

use IlluminateSupportServiceProvider;

and inside of the method boot();

Schema::defaultStringLength(191);

  1. Now delete the records in your database, user table for ex.

  2. run the following

php artisan config:cache

php artisan migrate

Community's user avatar

answered Apr 21, 2019 at 1:41

Levinski Polish's user avatar

1

Try with default string length 125 (for MySQL 8.0).

defaultStringLength(125)

answered May 20, 2021 at 17:45

Ajay's user avatar

AjayAjay

8288 silver badges17 bronze badges

I think to force StringLenght to 191 is a really bad idea.
So I investigate to understand what is going on.

I noticed that this message error :

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

Started to show up after I updated my MySQL version. So I’ve checked the tables with PHPMyAdmin and I’ve noticed that all the new tables created were with the collation utf8mb4_unicode_ci instead of utf8_unicode_ci for the old ones.

In my doctrine config file, I noticed that charset was set to utf8mb4, but all my previous tables were created in utf8, so I guess this is some update magic that it start to work on utf8mb4.

Now the easy fix is to change the line charset in your ORM config file.
Then to drop the tables using utf8mb4_unicode_ci if you are in dev mode or fixe the charset if you can’t drop them.

For Symfony 4

change charset: utf8mb4 to charset: utf8 in config/packages/doctrine.yaml

Now my doctrine migrations are working again just fine.

answered May 17, 2018 at 9:03

Kaizoku Gambare's user avatar

Kaizoku GambareKaizoku Gambare

3,0043 gold badges28 silver badges40 bronze badges

0

first delete all tables of the database in the localhost

Change Laravel default database (utf8mb4) properties in file config/database.php to:

‘charset’ => ‘utf8’,
‘collation’ => ‘utf8_unicode_ci’,

after then
Changing my local database properties utf8_unicode_ci.
php artisan migrate
it is ok.

answered Jul 7, 2019 at 20:59

Goldman.Vahdettin's user avatar

For anyone else who might run into this, my issue was that I was making a column of type string and trying to make it ->unsigned() when I meant for it to be an integer.

answered Apr 25, 2018 at 19:20

Brynn Bateman's user avatar

Brynn BatemanBrynn Bateman

7391 gold badge8 silver badges22 bronze badges

The approached that work here was pass a second param with the key name (a short one):

$table->string('my_field_name')->unique(null,'key_name');

answered Jul 24, 2018 at 13:23

Tiago Gouvêa's user avatar

Tiago GouvêaTiago Gouvêa

14.3k4 gold badges72 silver badges79 bronze badges

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and
privacy statement. We’ll occasionally send you account related emails.

Already on GitHub?
Sign in
to your account

Comments

@marcosjosemenezes

  • Laravel Version: 5.6.26
  • PHP Version: 7.1.16
  • Database Driver & Version: MySQL 5.7.21

Description:

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

Steps To Reproduce:

a. Cria-se um novo projeto: laravel new [project]
b. cd na pasta do [project] criada
c. Altera as informações do arquivo «.env» banco de dados
d. Executa o «php artisan migrate»

Qual a causa:

O limite de comprimento da chave UNIQUE KEY do MySQL é de 1000 bytes e o sistema esta tentando gerar uma chave maior.

Correção

a. Edite o arquivo «vendor laravel framework src Illuminate Database Schema Builder.php».
b. Faça a seguinte alteração
[código original] public static $defaultStringLength = 255;
[código alterado] public static $defaultStringLength = 250;
c. Remova as tabelas que foram criadas no banco de dados
— migrations
— users
d. Execute novamente o «php artisan migrate»
e. Pronto resolvido

@decadence

vpratfr, zeroterminal, ArnoutPullen, ultrono, aram810, esternwinluck, iTeije, vodd, crizise, abinash-mlbd, and 4 more reacted with thumbs up emoji
felix-penrose, 389883538, amineflex, petrnagy, clintontolbert, Illusionist3886, sapheko, and Sun3-11 reacted with thumbs down emoji
mohammedali933 reacted with laugh emoji
alnahian2003 reacted with confused emoji

@wellingguzman

A temporary solution would be going to your config/database.php and change the charset and collation from utf8mb4 to utf8

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

This happens because utf8mb4 uses 4 bytes per character, and the email column has a 255 character length which is greater than the limit 767 bytes. 255 x 4bytes = 1020b.

To fix this the email column length should be at most 191. 191 x 4 bytes = 764b.

marcosjosemenezes, HieuBk, borispacex, jasmanylara, comsianabrar, barcelonabk90, MohammadDayeh, rewindthetrend, 101t, compimprove, and 128 more reacted with thumbs up emoji
blancessanchez, sefirakarina, indrakumarprajapat, ultrono, bacnd, imyuvii, zamisyh, GeorgievAlex, bacardiel05, diazsmartiansyah, and 11 more reacted with laugh emoji
comrade-tea, prashantpatil14, jeni1616, Anas-shamia, sefirakarina, indrakumarprajapat, ultrono, bacnd, imyuvii, sinonodd, and 19 more reacted with hooray emoji
borispacex, Minpyaephyooo, compimprove, prashantpatil14, SamiKhan9892, jeni1616, Anas-shamia, sefirakarina, khalidsgh, srshubho, and 40 more reacted with heart emoji
imyuvii, zamisyh, farridkun, GeorgievAlex, bacardiel05, rgttamala, diazsmartiansyah, TheMrBlackLord, abinash-mlbd, diya-ing, and 14 more reacted with rocket emoji

@wellingguzman

@sisve

@wellingguzman How is that solution temporary? Can it be easily reverted and start working with utf8mb4 later on?

@wellingguzman

@sisve You can change it later on if you want to, this may not be the ideal solution if you want to use utf8mb4 charset.

There’s three way to solve this:

Changing the migration length to 191

Changing the length to 191 or less.

$table->string('name', 191);

Change the string default length

Changing the default (global) string type length to 191. This can be done using the schema facade.

IlluminateSupportFacadesSchema::defaultStringLength(191);

You can add this line to your AppServiceProvider.php boot() method located in app/Providers/ directory.

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

Use utf8 instead utf8mb4

This may not be the ideal one, but if you don’t care about utf8mb4 you can go to your config/database.php file and replace charset and collation to utf8

'charset' => 'utf8mb4',
'collation' => 'utf8mb4_unicode_ci',

to

'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
techadjuvant, pawansa3, rchen, Mukhami, SKIDDOW, Snackys07, ayatmustafa, mhdalkhiami, dhhdev, diniart, and 17 more reacted with thumbs up emoji
Mukhami, SKIDDOW, Snackys07, dhhdev, akbarSalahshour, and Waseem-Almoliky reacted with hooray emoji
KyriakosMilad, SKIDDOW, Snackys07, dhhdev, diniart, silvarney, akbarSalahshour, JoeBannouna, Waseem-Almoliky, and alnahian2003 reacted with heart emoji

@sisve

No, he cannot change it later. His database server will not allow it next week; the exact same problem will still be there. And he’ll have to write migrations to fix all the things you just told him to do.

A fourth alternative is to enable innodb_large_prefix in his database. That’s enabled per default in newer versions of mysql. Properly configuring the database server means he does not have to change his application code, and he can deploy the code to both an old or a new mysql versions, without changing any code.

@marcosjosemenezes

As explicações agregam a resposta, obrigado a todos.

@ghost

@tback

Still appears on clean laravel project:

  • Laravel 5.7.9
  • PHP 7.2.10-1+0~20181001133118.7+stretch~1.gbpb6e829
  • Mariadb 10.1.26-MariaDB-0+deb9u1

Project created with composer create-project --prefer-dist laravel/laravel auth.
All I did was change DB_CONNECTION in .env to mysql.
Then I called artisan migrate

This behavior is frustrating and confusing for new users. Please reopen the issue.

@sisve

Configure your database to enable innodb_large_prefix. It may require you to start using the new innodb_file_format Barracuda (that mysql is using as default now).

@jeni1616

A temporary solution would be going to your config/database.php and change the charset and collation from utf8mb4 to utf8

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

This happens because utf8mb4 uses 4 bytes per character, and the email column has a 255 character length which is greater than the limit 767 bytes. 255 x 4bytes = 1020b.

To fix this the email column length should be at most 191. 191 x 4 bytes = 764b.

Thanks, this worked !

@oubihis

Go in the AppProvidersAppServiceProvider class and change the boot method to look like this

use IlluminateSupportFacadesSchema;

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

@khanks

It seems obvious that newer versions of MySQL/MariaDB should not have this ‘key length’ error. But it also seems obvious to me that the solutions presented here have some issues of their own. Both Oracle and Percona have vacillated on turning innodb_large_prefix «ON» or «OFF» by default and both of them have it listed as ‘deprecated’ (Mysql ->https://dev.mysql.com/worklog/task/?id=7703, last paragraph says they will remove it. Percona docs have similar comments).
As for changing the AppServiceProvider ‘default’ string length, how does that help a situation where a developer specifically defines a varchar of 255? (side note: as a DB guy, I always wonder why anyone would define an index on a varchar).
Changing the collation seems, IMHO, to be the least fraught with weirdness (as long as you haven’t already stored data using utf8mb4 that actually required utf8mb4). Someone commented that «no, you cannot change it later». Well man, I’ve changed several of my databases back and forth from UTF-8 to UTF8MB4 a number of times and never had a problem. But I’m serving English-only users and they don’t use weird things like emoticons in a business website.
I realize I’ve not offered a great ‘solution’ for people (like me) who are not on the latest version of mysql/mariadb. I just thought these points needed to be brought up, for those who don’t already have enough to think about. Smile (no emoji needed to convey that).

@sisve

Hi @khanks ,

It sounds like you’re against modifying the innodb_large_prefix because Oracle/Percona have discussions about it. Just to clarify, the linked discussion argues for removing the setting entirely, and forcing it to the setting ON, which is my suggested solution for this problem. The last two paragraphs is interesting to read.

The parameter innodb_large_prefix was introduced in MySQL 5.5, so that users could avoid accidentally creating tables that would be incompatible with the InnoDB Plugin in MySQL 5.1. Now that MySQL 5.1 is not supported any more, it makes no sense to use any other value than innodb_large_prefix=ON.

Basically, the only purpose of innodb_file_format and innodb_large_prefix is to cripple the capabilities of InnoDB. This is the reason to change the default values to ‘uncrippled’ and to deprecate and remove the parameters for future removal, so that InnoDB cannot be accidentally crippled.

It was I that said that the collation couldn’t be changed later. The context is important, the poster cannot change the collation later because his database settings would still not allow it. If the correct settings where set, then the utf8mb4 collation can be used with the field sizes in question. My argument here was that it made more sense to modify those settings a year ago, when the question was asked, instead of waiting. They need to be changed someday anyhow.

@aleedhillon

If you are looking for a permanent solution then just change the default storage engine in Mysql ini configuration file to InnoDB which is the default storage engine in Mysql v5.5 and later.
default-storage-engine=InnoDB
In many cases like mine people complain that they have the latest version of Mysql but still having this error but the problem is sometime latest versions use old configuration files sitting in servers which uses MYISAM as default engine which create above problem.

@khanks

On 11/8/2019 2:13 PM, Ali A. Dhillon wrote:

If you are looking for a permanent solution then just change the
default storage engine in Mysql ini configuration file to *InnoDB*
which is the default storage engine in *Mysql v5.5* and later. In many
cases like mine people complain that they have the latest version of
Mysql but still having this error but the problem is sometime latest
versions use old configuration files stored in servers.
|default-storage-engine=InnoDB|


You are receiving this because you were mentioned.
Reply to this email directly, view it on GitHub
<#24711?email_source=notifications&email_token=AAG67TKAO773FLB4N42PLYDQSXB6JA5CNFSM4FHYIT62YY3PNVWWK3TUL52HS4DFVREXG43VMVBW63LNMVXHJKTDN5WW2ZLOORPWSZGOEDTHH2I#issuecomment-551973865>,
or unsubscribe
<https://github.com/notifications/unsubscribe-auth/AAG67TNQHW7A67IV4BMFKPTQSXB6JANCNFSM4FHYIT6Q>.

Thanks, that’s a great point. I don’t have that command specifically set
in my «my.ini», but I verified the default storage engine is InnoDb by
doing a «SHOW ENGINES» query. Good point though, and definitely worth
looking at.

@aleedhillon

@khanks I am using WAMP and in my case it had the old configuration my.ini which has the
default-storage-engine=MYISAM but in mysql v5.5 or latere InnoDB is default engine so if you just omit the above line (if there is any) it will use the default engine which is InnoDB.
So you don’t have to explicitly set the default-storage-engine=InnoDB if you are using mysql v5.5+. That’s why you don’t have this in you my.ini but still your storage engine is InnoDB.

If you omit the ENGINE option, the default storage engine is used. The default engine is InnoDB as of MySQL 5.5.5 (MyISAM before 5.5.5). You can specify the default engine by using the —default-storage-engine server startup option, or by setting the default-storage-engine option in the my.cnf configuration file.Ref

@farridkun

A temporary solution would be going to your config/database.php and change the charset and collation from utf8mb4 to utf8

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

This happens because utf8mb4 uses 4 bytes per character, and the email column has a 255 character length which is greater than the limit 767 bytes. 255 x 4bytes = 1020b.

To fix this the email column length should be at most 191. 191 x 4 bytes = 764b.

This is Work for me, Thanks Dude!

@prabaharanh

A temporary solution would be going to your config/database.php and change the charset and collation from utf8mb4 to utf8

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

This happens because utf8mb4 uses 4 bytes per character, and the email column has a 255 character length which is greater than the limit 767 bytes. 255 x 4bytes = 1020b.

To fix this the email column length should be at most 191. 191 x 4 bytes = 764b.

Success!!!!

@israelkingz

A temporary solution would be going to your config/database.php and change the charset and collation from utf8mb4 to utf8

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

This happens because utf8mb4 uses 4 bytes per character, and the email column has a 255 character length which is greater than the limit 767 bytes. 255 x 4bytes = 1020b.
To fix this the email column length should be at most 191. 191 x 4 bytes = 764b.

Thanks, this worked !

Thanks, It worked

@caiofelipedossantos

@khanks I am using WAMP and in my case it had the old configuration my.ini which has the
default-storage-engine=MYISAM but in mysql v5.5 or latere InnoDB is default engine so if you just omit the above line (if there is any) it will use the default engine which is InnoDB.
So you don’t have to explicitly set the default-storage-engine=InnoDB if you are using mysql v5.5+. That’s why you don’t have this in you my.ini but still your storage engine is InnoDB.

If you omit the ENGINE option, the default storage engine is used. The default engine is InnoDB as of MySQL 5.5.5 (MyISAM before 5.5.5). You can specify the default engine by using the —default-storage-engine server startup option, or by setting the default-storage-engine option in the my.cnf configuration file.Ref

Thanks, It worked.

@khanks

Thanks. I figured out a solution long ago. And when my host finally updates
the version of MySQL that they provide, it will be a non-issue.
Also, there are about 50 duplicates of this same answer and every time
somebody posts one of those duplicates, I get copied on it — and probably
many others do as well. So maybe we shouldn’t pursue this thread anymore.
The real question for me, was why in the hell anybody would define an email
field as big as Laravel defined that default. it’s ridiculous.

On Fri, Jun 26, 2020, 8:59 PM Caio Felipe ***@***.***> wrote:
@khanks <https://github.com/khanks> I am using WAMP and in my case it had
the old configuration my.ini which has the
default-storage-engine=MYISAM but in mysql v5.5 or latere InnoDB is
default engine so if you just omit the above line (if there is any) it will
use the default engine which is InnoDB.
So you don’t have to explicitly set the default-storage-engine=InnoDB if
you are using mysql v5.5+. That’s why you don’t have this in you my.ini but
still your storage engine is InnoDB.

If you omit the ENGINE option, the default storage engine is used. The
default engine is InnoDB as of MySQL 5.5.5 (MyISAM before 5.5.5). You can
specify the default engine by using the —default-storage-engine server
startup option, or by setting the default-storage-engine option in the
my.cnf configuration file.Ref
<https://dev.mysql.com/doc/refman/5.5/en/storage-engine-setting.html>

Thanks, It worked.


You are receiving this because you were mentioned.
Reply to this email directly, view it on GitHub
<#24711 (comment)>,
or unsubscribe
<https://github.com/notifications/unsubscribe-auth/AAG67TNBRXADWHOZL6GANCTRYVHAXANCNFSM4FHYIT6Q>
.

@khanks

In addition, my default storage engine has always been Innodb — I don’t
even use Myisam.

On Fri, Jun 26, 2020, 9:27 PM Smiddick Hanks ***@***.***> wrote:
Thanks. I figured out a solution long ago. And when my host finally
updates the version of MySQL that they provide, it will be a non-issue.
Also, there are about 50 duplicates of this same answer and every time
somebody posts one of those duplicates, I get copied on it — and probably
many others do as well. So maybe we shouldn’t pursue this thread anymore.
The real question for me, was why in the hell anybody would define an email
field as big as Laravel defined that default. it’s ridiculous.

On Fri, Jun 26, 2020, 8:59 PM Caio Felipe ***@***.***>
wrote:

> @khanks <https://github.com/khanks> I am using WAMP and in my case it
> had the old configuration my.ini which has the
> default-storage-engine=MYISAM but in mysql v5.5 or latere InnoDB is
> default engine so if you just omit the above line (if there is any) it will
> use the default engine which is InnoDB.
> So you don’t have to explicitly set the default-storage-engine=InnoDB if
> you are using mysql v5.5+. That’s why you don’t have this in you my.ini but
> still your storage engine is InnoDB.
>
> If you omit the ENGINE option, the default storage engine is used. The
> default engine is InnoDB as of MySQL 5.5.5 (MyISAM before 5.5.5). You can
> specify the default engine by using the —default-storage-engine server
> startup option, or by setting the default-storage-engine option in the
> my.cnf configuration file.Ref
> <https://dev.mysql.com/doc/refman/5.5/en/storage-engine-setting.html>
>
> Thanks, It worked.
>
> —
> You are receiving this because you were mentioned.
> Reply to this email directly, view it on GitHub
> <#24711 (comment)>,
> or unsubscribe
> <https://github.com/notifications/unsubscribe-auth/AAG67TNBRXADWHOZL6GANCTRYVHAXANCNFSM4FHYIT6Q>
> .
>

@skino2019

A temporary solution would be going to your config/database.php and change the charset and collation from utf8mb4 to utf8

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

This happens because utf8mb4 uses 4 bytes per character, and the email column has a 255 character length which is greater than the limit 767 bytes. 255 x 4bytes = 1020b.

To fix this the email column length should be at most 191. 191 x 4 bytes = 764b.

This fixed it for me. when i created the DB it set to utf8mb and collation utf8mb_general_ci… changed the formatting and worked out the box.

@anasroud

A temporary solution would be going to your config/database.php and change the charset and collation from utf8mb4 to utf8

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

This happens because utf8mb4 uses 4 bytes per character, and the email column has a 255 character length which is greater than the limit 767 bytes. 255 x 4bytes = 1020b.

To fix this the email column length should be at most 191. 191 x 4 bytes = 764b.

This fixed it for me. thank you so much.

@Alexis2421

@sisve Puede cambiarlo más adelante si lo desea, esta puede no ser la solución ideal si desea usar utf8mb4charset.

Hay tres formas de resolver esto:

Cambiar la duración de la migración a 191

Cambiando la longitud 191ao menos.

$table->string('name', 191);

Cambiar la longitud predeterminada de la cadena

Cambiar la stringlongitud de tipo predeterminada (global) a 191. Esto se puede hacer usando la fachada del esquema.

IlluminateSupportFacadesSchema::defaultStringLength(191);

Puede agregar esta línea a su AppServiceProvider.php boot()método ubicado en el app/Providers/directorio.

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

Utilizar en su utf8lugarutf8mb4

Esto puede no ser la ideal, pero si no se preocupan por utf8mb4usted puede ir a su config/database.phparchivo y reemplazar charsety collationalutf8

'charset' => 'utf8mb4',
'collation' => 'utf8mb4_unicode_ci',

a

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

Muchas Gracias, la solución para mi fue cambiar la longitud a 191, pero primero revise que hubiera borrado en la base de datos las migraciones que había podido realizar, y luego ejecutar nuevamente el comando php artisan migrate

@anopchaksu

simpley login to phpmyadmin of hosting account and select database >> go to «operations» >> change the collections to ‘utf8mb4_unicode_ci’ and restored backup now work for me.

@Lakshsay

PLEASE ANYONE HELP?

IlluminateDatabaseQueryException

SQLSTATE[42S02]: Base table or view not found: 1146 Table ‘hello.core_settings’ doesn’t exist (SQL: select * from core_settings where name = site_locale limit 1)

at vendor/laravel/framework/src/Illuminate/Database/Connection.php:671
667| // If an exception occurs when attempting to run a query, we’ll format the error
668| // message to include the bindings with SQL, which will make this exception a
669| // lot more helpful to the developer instead of just the database’s errors.
670| catch (Exception $e) {

671| throw new QueryException(
672| $query, $this->prepareBindings($bindings), $e
673| );
674| }
675|

1 [internal]:0
IlluminateFoundationApplication::IlluminateFoundation{closure}(Object(AppProvidersAppServiceProvider))

14 modules/Core/Models/Settings.php:31
IlluminateDatabaseEloquentBuilder::first()

@caiofelipedossantos

Good afternoon @Lakshsay, could I put the Model Settings source code?
Apparently the table name is wrong — hello.core_settings.

@Lakshsay

@polares552 Yes please advice me the steps / changes needs to be done.
where exactly I need to make changes.
im a student so learning

@caiofelipedossantos

@Lakshsay add your application’s source code here or provide the repository link so we can help you.
You can start by checking your migrations, the migrations are inside the databases folder.
If you haven’t created it, make sure the connection to your database is working, the connection settings can be adjusted in the .env file at the root of the project, then run the command php artisan migrate in your command terminal.
Check your controller where the SQL statement is being assembled via Eloquent or QueryBuilder.
If you prefer you can call me on Skype caiofelipe.up@hotmail.com.

@Lakshsay

@polares552 best personality I have ever came across. you are so helpful , polite and understandable. listened to all the concerns and resolved it I am really thankful to you.

@caiofelipedossantos

@polares552 best personality I have ever came across. you are so helpful , polite and understandable. listened to all the concerns and resolved it I am really thankful to you.

Thanks!!!

@felipeminello

A temporary solution would be going to your config/database.php and change the charset and collation from utf8mb4 to utf8

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

This happens because utf8mb4 uses 4 bytes per character, and the email column has a 255 character length which is greater than the limit 767 bytes. 255 x 4bytes = 1020b.

To fix this the email column length should be at most 191. 191 x 4 bytes = 764b.

THANKS!
Works on Heroku

@putroandrianto

A temporary solution would be going to your config/database.php and change the charset and collation from utf8mb4 to utf8

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

This happens because utf8mb4 uses 4 bytes per character, and the email column has a 255 character length which is greater than the limit 767 bytes. 255 x 4bytes = 1020b.
To fix this the email column length should be at most 191. 191 x 4 bytes = 764b.

This fixed it for me. thank you so much.

wow thanks

Странная ошибка, возникающая при выполнении первой миграции в Laravel 8, тянется ещё со времён Laravel 5.4. И её почему-то до сих пор не устранили. Связано ли это с тем, что программисты, работающие с Laravel, предпочитают исключительно MySQL и люто ненавидят MariaDB, или ещё по какой причине, но ошибка случается и поправить её на самом деле, не составляет труда.

Ошибка выглядит следующим образом. При выполнении команды:

php artisan migrate

Миграции начинают обрабатываться:

Migration table created successfully.
Migrating: 2014_10_12_000000_create_users_table

Но тут же вылетает сообщение об ошибке:

   IlluminateDatabaseQueryException

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

  at vendor/laravel/framework/src/Illuminate/Database/Connection.php:671
    667▕         // If an exception occurs when attempting to run a query, we'll format the error
    668▕         // message to include the bindings with SQL, which will make this exception a
    669▕         // lot more helpful to the developer instead of just the database's errors.
    670▕         catch (Exception $e) {
  ➜ 671▕             throw new QueryException(
    672▕                 $query, $this->prepareBindings($bindings), $e
    673▕             );
    674▕         }
    675▕

      +9 vendor frames
  10  database/migrations/2014_10_12_000000_create_users_table.php:26
      IlluminateSupportFacadesFacade::__callStatic("create")

      +21 vendor frames
  32  artisan:37
      IlluminateFoundationConsoleKernel::handle(Object(SymfonyComponentConsoleInputArgvInput), Object(SymfonyComponentConsoleOutputConsoleOutput))

Решение проблемы с ошибкой php artisan migrate — SQLSTATE[42000]: Syntax error or access violation: 1071 Specified key was too long; max key length is 767 bytes при применении миграции в Laravel

Для устранения этой ошибки нужно внести изменения в метод boot класса AppServiceProvider. Для этого открываем файл, находящийся по адресу:

/папка_проекта/app/Providers/AppServiceProvider.php

Изначально он имеет вид:

<?php

namespace AppProviders;

use IlluminateSupportServiceProvider;

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

    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        //
    }
}

В него нужно вписать 2 строчки (использование библиотеки фасадов use IlluminateSupportFacadesSchema; и модификацию метода bootSchema::defaultStringLength(191);) таким вот образом:

use IlluminateSupportFacadesSchema;

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

Таким образом модифицированный файл с классом AppServiceProvider будет иметь вид (добавляется 6-я и 26-я строки):

<?php

namespace AppProviders;

use IlluminateSupportServiceProvider;
use IlluminateSupportFacadesSchema;
class AppServiceProvider extends ServiceProvider
{
    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        //
    }

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

После сохранения этих изменений, команда php artisan migrate работает без ошибок, все миграции применяются и проект на фреймворке Laravel оживает. =)

Важно(!)
Перед тем, как накатывать повторно миграции, удалите созданные ранее таблицы из базы данных.
Иначе будет новая ошибка! ;)

По материалам:
laravel-news.com

Заберите ссылку на статью к себе, чтобы потом легко её найти!
Выберите, то, чем пользуетесь чаще всего:

Согласно информации портала laravel-news, начиная с версии Laravel 5.4 были внесены изменения в дефолтный charset базы данных. Если быть более точным, то 25.10.2016 года Taylor Otwell сделал соответствующий коммит с аннотацией «use utf8mb4 as default character set». Данная кодировка поддерживает хранение emoji.

Таким образом, во всех современных релизах Laravel, после 25.10.16 установлена кодировка по умолчанию utf8mb4. Именно она и вызывает ошибку Specified key was too long. Однако, ошибка не должна проявляться при выполнении миграции для БД MySQL v5.7.7 или старше или MariaDB старше чем 10.2.2.

Но что же делать, если у Вас все таки при выполнении миграций:

php artisan migrate

 в консоли появляется вот такая неприятная ошибка?

IlluminateDatabaseQueryException  : SQLSTATE[42000]: Syntax error or access violation: 1071 Specified key was too long; max key length is 1000 bytes (SQL: alter table `users` add unique `users_email_unique`(`email`))

Exception trace:

1   DoctrineDBALDriverPDOException::("SQLSTATE[42000]: Syntax error or access violation: 1071 Specified key was too long; max key length is 1000 bytes")

Ну что же, если Вам не повезло и подобная ошибка все таки появилась — не расстраивайтесь. Она довольно быстро и легко исправляется и сейчас я расскажу, как это можно сделать.

Варианты исправления ошибки Laravel: Specified key was too long

Собственно, как и всегда, у нас на выбор есть несколько вариантов решения данной проблемы. Рассмотрим их далее по очереди:

1. Переход на более новую версию MySQL

Это наиболее очевидный вариант. И если вы только создаете новое приложение, то конечно же лучше сразу выбрать более новую версию MySQL. Зачем разрабатывать на устаревших технологиях? Но! Если у вас шаред хостинг, то скорее всего опция смены версии БД у вас отсутствует.

2.  Изменить параметр defaultStringLegth

Если открыть оф. документацию Laravel в разделе «Создание Индексов», то разработчики фреймворка советуют установить вручную параметр defaultStringLegth равным 191 символам для более старых версий MySQL или MariaDB. Сделать это возможно, вызвав метод Schema::defaultStringLength внутри AppServiceProvider. Для этого открываем файл:

nano app/Providers/AppServiceProvider.php

и добавляем вызов в методе boot, предварительно импортировав неймспейс Schema:

use IlluminateSupportFacadesSchema;

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

После этого Ваши миграции будут успешно выполняться.

3. Уменьшить длину строки в отдельно взятой миграции

Вместо глобального изменения длины строки для всех миграций, возможно изменить длину строки непосредственно для определенной таблицы. К примеру, изменим значение длины строки для миграции, создающей таблицу пользователей:

Schema::defaultStringLength(191);

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

4. Уменьшить длину индекса, но не уменьшать длину строки

Аналогично, тому как можно устанавливать длину строки непосредственно при выполнении миграции в отедльно взятую таблицу, можно уменьшить длину индекса в поле, но не уменьшать при этом длину самого поля. Для этого все в том же файле миграции нужно добавить:

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

5. Изменить кодировку в таблице на utf8

Не знаю как Вам, но лично мне не сильно нравится рекомендуемый вариант с уменьшением длины строки. Вместо этого я предпочитаю изменить кодировку по умолчанию в своей БД на utf8, т.к. хранить emoji я в ней явно не планирую. За одно я всегда помимо смены кодировки (charset), еще и меняю сравнение (collation) на utf8_general_ci. Для этого в файле конфигурации БД:

nano app/config/database.php

я меняю для mySQL соответствующие значения на:

'charset' => 'utf8',
'collation' => 'utf8_general_ci',

Теперь у Вас всё должно работать как полагается! Если у Вас остались вопросы — смело задавайте в комментариях.

Содержание

  1. Laravel 8.x: Ошибка php artisan migrate — SQLSTATE[42000]: Syntax error or access violation: 1071 Specified key was too long; max key length is 767 bytes
  2. Решение проблемы с ошибкой php artisan migrate — SQLSTATE[42000]: Syntax error or access violation: 1071 Specified key was too long; max key length is 767 bytes при применении миграции в Laravel
  3. Laravel по-русски
  4. #1 06.03.2017 14:24:22
  5. Ошибка при выполнение миграции
  6. #2 06.03.2017 14:52:51
  7. Re: Ошибка при выполнение миграции
  8. #3 06.03.2017 16:58:44
  9. Re: Ошибка при выполнение миграции
  10. #4 06.03.2017 17:03:53
  11. Re: Ошибка при выполнение миграции
  12. #5 06.03.2017 17:26:43
  13. Re: Ошибка при выполнение миграции
  14. #6 06.03.2017 17:31:47
  15. Re: Ошибка при выполнение миграции
  16. #7 06.03.2017 17:31:59
  17. Re: Ошибка при выполнение миграции
  18. #8 06.03.2017 17:53:02
  19. Re: Ошибка при выполнение миграции
  20. #9 06.03.2017 20:38:16
  21. Re: Ошибка при выполнение миграции
  22. Sqlstate 42000 syntax error or access violation 1071 laravel
  23. How to Fix Laravel Syntax Error or Access Violation 1071
  24. Conclusion
  25. Laravel по-русски
  26. #1 23.04.2018 09:23:06
  27. Ошибка при создание миграции
  28. #2 23.04.2018 09:56:53
  29. Re: Ошибка при создание миграции
  30. #3 23.04.2018 10:32:58
  31. Re: Ошибка при создание миграции
  32. #4 23.04.2018 10:55:34
  33. Re: Ошибка при создание миграции
  34. #5 23.04.2018 10:58:12
  35. Re: Ошибка при создание миграции
  36. #6 23.04.2018 11:03:00
  37. Re: Ошибка при создание миграции
  38. #7 23.04.2018 11:05:29
  39. Re: Ошибка при создание миграции
  40. #8 23.04.2018 11:06:20
  41. Re: Ошибка при создание миграции
  42. #9 23.04.2018 11:13:41
  43. Re: Ошибка при создание миграции
  44. #10 23.04.2018 11:16:19
  45. Re: Ошибка при создание миграции
  46. #11 23.04.2018 11:22:07
  47. Re: Ошибка при создание миграции

Laravel 8.x: Ошибка php artisan migrate — SQLSTATE[42000]: Syntax error or access violation: 1071 Specified key was too long; max key length is 767 bytes

Странная ошибка, возникающая при выполнении первой миграции в Laravel 8, тянется ещё со времён Laravel 5.4. И её почему-то до сих пор не устранили. Связано ли это с тем, что программисты, работающие с Laravel, предпочитают исключительно MySQL и люто ненавидят MariaDB, или ещё по какой причине, но ошибка случается и поправить её на самом деле, не составляет труда.

Ошибка выглядит следующим образом. При выполнении команды:

Миграции начинают обрабатываться:

Но тут же вылетает сообщение об ошибке:

Решение проблемы с ошибкой php artisan migrate — SQLSTATE[42000]: Syntax error or access violation: 1071 Specified key was too long; max key length is 767 bytes при применении миграции в Laravel

Для устранения этой ошибки нужно внести изменения в метод boot класса AppServiceProvider . Для этого открываем файл, находящийся по адресу:

Изначально он имеет вид:

В него нужно вписать 2 строчки (использование библиотеки фасадов use IlluminateSupportFacadesSchema; и модификацию метода boot : Schema::defaultStringLength(191); ) таким вот образом:

Таким образом модифицированный файл с классом AppServiceProvider будет иметь вид (добавляется 6-я и 26-я строки):

После сохранения этих изменений, команда php artisan migrate работает без ошибок, все миграции применяются и проект на фреймворке Laravel оживает. =)

Важно(!)
Перед тем, как накатывать повторно миграции, удалите созданные ранее таблицы из базы данных.
Иначе будет новая ошибка! 😉

Заберите ссылку на статью к себе, чтобы потом легко её найти!
Выберите, то, чем пользуетесь чаще всего:

Источник

Laravel по-русски

Русское сообщество разработки на PHP-фреймворке Laravel.

#1 06.03.2017 14:24:22

Ошибка при выполнение миграции

При выполнение в консоли миграции выдает такую оишбку

php artisan migrate
Migration table created successfully.

[IlluminateDatabaseQueryException]
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_uniq
ue`(`email`))

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

Хотя с таблицей users я не работал создал свою таблицу

Не в сети 03.12.2016

#2 06.03.2017 14:52:51

Re: Ошибка при выполнение миграции

Не в сети 19.02.2015

#3 06.03.2017 16:58:44

Re: Ошибка при выполнение миграции

Выполнил таже самая ошибка

Не в сети 03.12.2016

#4 06.03.2017 17:03:53

Re: Ошибка при выполнение миграции

[ErrorException]
Missing argument 1 for IlluminateDatabaseSchemaBuilder::defaultStringLength(), c
alled in D:OpenServerdomainstravel.locvendorlaravelframeworksrcIlluminateS
upportFacadesFacade.php on line 221 and defined

Не в сети 03.12.2016

#5 06.03.2017 17:26:43

Re: Ошибка при выполнение миграции

забыл параметр передать?

Не в сети 19.02.2015

#6 06.03.2017 17:31:47

Re: Ошибка при выполнение миграции

забыл параметр передать?

передавал все равно не работает

Не в сети 03.12.2016

#7 06.03.2017 17:31:59

Re: Ошибка при выполнение миграции

[IlluminateDatabaseQueryException]
SQLSTATE[42S01]: Base table or view already exists: 1050 Table ‘users’ already exis
ts (SQL: create table `users` (`id` int unsigned not null auto_increment primary ke
y, `name` varchar(191) not null, `email` varchar(191) not null, `password` varchar(
191) not null, `remember_token` varchar(100) null, `created_at` timestamp null, `up
dated_at` timestamp null) default character set utf8mb4 collate utf8mb4_unicode_ci)

[PDOException]
SQLSTATE[42S01]: Base table or view already exists: 1050 Table ‘users’ already exis
ts

Не в сети 03.12.2016

#8 06.03.2017 17:53:02

Re: Ошибка при выполнение миграции

Ну так сперва надо удалить все таблицы из базы которые создаются миграциями.

Не в сети 01.09.2016

#9 06.03.2017 20:38:16

Re: Ошибка при выполнение миграции

Удалил таблицу, миграция выполнилась, таблица создалась но все равно выдает такую ошибку
[IlluminateDatabaseQueryException]
SQLSTATE[42000]: Syntax error or access violation: 1071 Specified key was too long;
max key length is 767 bytes (SQL: alter table `menus` add unique `menus_alias_uniq
ue`(`alias`))

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

Источник

Sqlstate 42000 syntax error or access violation 1071 laravel

I’ve just upgraded to Laravel 5.4 and created my first project with it. When I first try to migrate the database, I get this error : n

SQLSTATE[42000]: Syntax error or access violation: 1071 Specified key was too long; max key length is 1000 bytes (SQL: alter table users add unique users_email_unique ( email )) n n

I can fix this by going in the migration for the users table, and manually specifying the max-length of the email field, like so : n

$table->string(’email’, 250)->unique();n n

If I run php artisan migrate again, it will work for the users table, but will fail for the password reset table. I have to do the same thing for the email field in that migration. n

Has anyone else encountered this issue? It was working fine before with 5.3. n

The solution was to add this line in the boot() method of the AppServiceProvider : n

(don’t forget to import the namespace) n

Schema::defaultStringLength(191); works well n»,»bodyInMarkdown»:»Schema::defaultStringLength(191); works well»,»replies»:[<«id»:779874,»conversation_id»:53568,»body»:»

I do have this issue now: n

ClassnApp\Providers\Schema not found n

If you are using MariaDB or an older version of MySQL, you need to place this code in your AppServiceProvider.php : n

use Illuminate\Support\Facades\Schema;nnpublic function boot()n<n Schema::defaultStringLength(191);n>n n»,»bodyInMarkdown»:»If you are using MariaDB or an older version of MySQL, you need to place this code in your `AppServiceProvider.php`:rn«`rnuse Illuminate\Support\Facades\Schema;rnrnpublic function boot()rn<rn Schema::defaultStringLength(191);rn>rn«`»,»replies»:[<«id»:698111,»conversation_id»:53568,»body»:»

This fixed it for me: n

Inside config/database.php , replace this line for mysql n

‘engine’ => null’,n n

‘engine’ => ‘InnoDB ROW_FORMAT=DYNAMIC’,n n

Instead of setting a limit on your string lenght. n»,»bodyInMarkdown»:»This fixed it for me:rnrnInside `config/database.php`, replace this line for mysqlrnrn«`rn’engine’ => null’,rn«`rnwithrn«`rn’engine’ => ‘InnoDB ROW_FORMAT=DYNAMIC’,rn«`rnInstead of setting a limit on your string lenght.rn»,»replies»:[<«id»:682847,»conversation_id»:53568,»body»:»

Is there another engine option for MySQL which can solve the UTF8MB4 issue as well as allow FK constraints in the standard way, or can MyISAM handle it with some other small change? I’m running MySQL 5.7.11 locally, but the application will eventually run in the cloud and needs to be robust for any MySQL db. n

Thank you for any help. n

I found easiest to set in migration; n

Can someone please explain why this is happening ? n

I can’t even use factory’s or seeding properly anymore. I try to seed my CRM with companies and if I set my seeder to say «5», all is fine. if I try 50. I get that error. AND I am using n

SQLSTATE[42000]: Syntax error or access violation: 1071 Specified key was too long; n

There is a good explanation of why this happens on Servers for Hackers — which I was surprised to see is now over 2 years old. n

It details strategies for dealing with this issue n

Источник

How to Fix Laravel Syntax Error or Access Violation 1071

Get real time updates directly on you device, subscribe now.

In this article, we will discuss the most common issue “How to Fix Laravel Syntax Error or Access Violation 1071”. When we start a new project within Laravel then we face this.

An exception is thrown because Laravel made a change to the default database character set, and it’s now utf8mb4 which includes support for storing emojis. This only affects new applications and as long as you are running MySQL v5.7.7 and higher you do not need to do anything.

For those running MariaDB or older versions of MySQL you may hit this error when trying to run migrations:

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

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

You can fix this error using the following solution.

Update the AppServiceProvider.php located at app/providers.

After, updating the AppServiceProvider.php. The migrate command executed without any issue.

Conclusion

In this article, I’m trying to explain to you the How you can fix the Laravel Syntax Error or Access Violation 1071. Hope you like this article. Please feel free to add the comment if any query or you can submit your feedback 🙂

You may like

If you like our content, please consider buying us a coffee.
Thank you for your support!

Источник

Laravel по-русски

Русское сообщество разработки на PHP-фреймворке Laravel.

#1 23.04.2018 09:23:06

Ошибка при создание миграции

Не могу понять почему есть ошибка при создание миграции

GaneMax@GANEMAX D:OSPaneldomainscatalog.loc
$ php artisan migrate

IlluminateDatabaseQueryException : SQLSTATE[42S01]: Base table or view already exists: 1050 Table ‘users’ already exists (SQL: create table `users` (`id` int unsigned not null auto_increment primary key, `name` varchar(255) not null, `email` varchar(255) not null, `password` varchar(255) not null, `remember_token` varchar(100) null, `created_at` timestamp null, `updated_at` timestamp null) default character set utf8mb4 collate utf8mb4_unicode_ci)

at D:OSPaneldomainscatalog.locvendorlaravelframeworksrcIlluminateDatabaseConnection.php:664
660| // If an exception occurs when attempting to run a query, we’ll format the error
661| // message to include the bindings with SQL, which will make this exception a
662| // lot more helpful to the developer instead of just the database’s errors.
663| catch (Exception $e) <
> 664| throw new QueryException(
665| $query, $this->prepareBindings($bindings), $e
666| );
667| >
668|

1 PDOException::(«SQLSTATE[42S01]: Base table or view already exists: 1050 Table ‘users’ already exists»)
D:OSPaneldomainscatalog.locvendorlaravelframeworksrcIlluminateDatabaseConnection.php:458

2 PDOStatement::execute()
D:OSPaneldomainscatalog.locvendorlaravelframeworksrcIlluminateDatabaseConnection.php:458

Please use the argument -v to see more details.

Не в сети 03.12.2016

#2 23.04.2018 09:56:53

Re: Ошибка при создание миграции

Подскажите как устранить ?

Не в сети 03.12.2016

#3 23.04.2018 10:32:58

Re: Ошибка при создание миграции

Он Вам пишет, что таблица users уже существует.
Т.е. при запуске artisan migration, скрипт выполняет все миграции, которые ранее не были выполнены.
Возможно, таблицу users Вы создавали вручную, а потом создали миграцию.
Если Вам эту таблицу users не жалко, удалите ее. Или переименуйте, выполните миграцию, а потом переименуйте обратно ))

Не в сети 22.10.2017

#4 23.04.2018 10:55:34

Re: Ошибка при создание миграции

Я все таблице с БД удалил, так там может быть users таблица

Не в сети 03.12.2016

#5 23.04.2018 10:58:12

Re: Ошибка при создание миграции

значит не в той базе удалили. или не в ту базу пишет миграция.
Проверьте в файле .env
DB_DATABASE=»Та база»?

Не в сети 22.10.2017

#6 23.04.2018 11:03:00

Re: Ошибка при создание миграции

значит не в той базе удалили. или не в ту базу пишет миграция. Проверьте в файле .envDB_DATABASE=»Та база»?

да DB_DATABASE=catalog
я все с БД удалил, выполняю миграцию создаеться таблица users migrtion и все

Не в сети 03.12.2016

#7 23.04.2018 11:05:29

Re: Ошибка при создание миграции

Может кодировка не та

Не в сети 03.12.2016

#8 23.04.2018 11:06:20

Re: Ошибка при создание миграции

Создалось 2 таблицы: users и migration, да? Хорошо.
Файл миграции для таблицы categories в папке database/migrations ?

Не в сети 22.10.2017

#9 23.04.2018 11:13:41

Re: Ошибка при создание миграции

Не в сети 03.12.2016

#10 23.04.2018 11:16:19

Re: Ошибка при создание миграции

1. Сейчас команда artisan migrate ошибок не выдает?
2. Что выводит команда artisan migrate:status ?
3. Имя файла миграции для категорий?
() Вы запускаете artisan в папке того проекта? )) На всякий случай

Не в сети 22.10.2017

#11 23.04.2018 11:22:07

Re: Ошибка при создание миграции

IlluminateDatabaseQueryException : SQLSTATE[42S01]: Base table or view already exists: 1050 Table ‘users’ already exists (SQL: create table `users` (`id` int unsigned not null auto_increment primary key, `name` varchar(255) not null, `email` varchar(255) not null, `password` varchar(255) not null, `remember_token` varchar(100) null, `created_at` timestamp null, `updated_at` timestamp null) default character set utf8mb4 collate utf8mb4_unicode_ci)

at D:OSPaneldomainscatalog.locvendorlaravelframeworksrcIlluminateDatabaseConnection.php:664
660| // If an exception occurs when attempting to run a query, we’ll format the error
661| // message to include the bindings with SQL, which will make this exception a
662| // lot more helpful to the developer instead of just the database’s errors.
663| catch (Exception $e) <
> 664| throw new QueryException(
665| $query, $this->prepareBindings($bindings), $e
666| );
667| >
668|

1 PDOException::(«SQLSTATE[42S01]: Base table or view already exists: 1050 Table ‘users’ already exists»)
D:OSPaneldomainscatalog.locvendorlaravelframeworksrcIlluminateDatabaseConnection.php:458

2 PDOStatement::execute()
D:OSPaneldomainscatalog.locvendorlaravelframeworksrcIlluminateDatabaseConnection.php:458

Please use the argument -v to see more details.

Имя файла миграции для категорий?
2018_04_23_062130_create_categories_table
Создавал файл миграции так
$ php artisan make:migration create_categories_table —create=categories

Источник

#1 06.03.2017 14:24:22

Ошибка при выполнение миграции

При выполнение в консоли миграции выдает такую оишбку

php artisan migrate
Migration table created successfully.

  [IlluminateDatabaseQueryException]
  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_uniq
  ue`(`email`))

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

Хотя с таблицей users я не работал создал свою таблицу

<?php

use IlluminateSupportFacadesSchema;
use IlluminateDatabaseSchemaBlueprint;
use IlluminateDatabaseMigrationsMigration;

class CreateMenusTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('menus', function (Blueprint $table) {
            $table->increments('id');
            $table->string('title', 200);
            $table->string('alias', 200)->unique();
            $table->integer('position')->nullable();
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('menus');
    }
}

#2 06.03.2017 14:52:51

Re: Ошибка при выполнение миграции

#3 06.03.2017 16:58:44

Re: Ошибка при выполнение миграции

Выполнил таже самая ошибка

#4 06.03.2017 17:03:53

Re: Ошибка при выполнение миграции

[ErrorException]
  Missing argument 1 for IlluminateDatabaseSchemaBuilder::defaultStringLength(), c
  alled in D:OpenServerdomainstravel.locvendorlaravelframeworksrcIlluminateS
  upportFacadesFacade.php on line 221 and defined

#5 06.03.2017 17:26:43

Re: Ошибка при выполнение миграции

забыл параметр передать?

#6 06.03.2017 17:31:47

Re: Ошибка при выполнение миграции

constb пишет:

забыл параметр передать?

передавал все равно не работает

#7 06.03.2017 17:31:59

Re: Ошибка при выполнение миграции

[IlluminateDatabaseQueryException]
  SQLSTATE[42S01]: Base table or view already exists: 1050 Table ‘users’ already exis
  ts (SQL: create table `users` (`id` int unsigned not null auto_increment primary ke
  y, `name` varchar(191) not null, `email` varchar(191) not null, `password` varchar(
  191) not null, `remember_token` varchar(100) null, `created_at` timestamp null, `up
  dated_at` timestamp null) default character set utf8mb4 collate utf8mb4_unicode_ci)

  [PDOException]
  SQLSTATE[42S01]: Base table or view already exists: 1050 Table ‘users’ already exis
  ts

#8 06.03.2017 17:53:02

Re: Ошибка при выполнение миграции

Ну так сперва надо удалить все таблицы из базы которые создаются миграциями.

#9 06.03.2017 20:38:16

Re: Ошибка при выполнение миграции

Удалил таблицу, миграция выполнилась, таблица создалась но все равно выдает такую ошибку
  [IlluminateDatabaseQueryException]
  SQLSTATE[42000]: Syntax error or access violation: 1071 Specified key was too long;
   max key length is 767 bytes (SQL: alter table `menus` add unique `menus_alias_uniq
  ue`(`alias`))

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

#10 07.03.2017 05:41:48

Re: Ошибка при выполнение миграции

убери 200 из параметров ->string() в миграциях

#12 16.05.2017 02:49:33

Re: Ошибка при выполнение миграции

Дружище, обнови MySql до версии 5.7 и будет тебе счастье

Понравилась статья? Поделить с друзьями:

Читайте также:

  • La noire ошибка передачи файла
  • Laravel return custom error
  • Laravel return back with error
  • La noire ошибка отсутствует dll переустановите social club на пиратке
  • La noire ошибка gsrld dll

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии