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

Instead of adding Schema::defaultStringLength(191); in the AppServiceProvider  boot method as described below, rather upgrade your version of MariaDB as outlined in our How to upgrade MariaDB from 10.1 to 10.3 Ubuntu Bionic (18.04) LTS Server Knowledgebase article.

Otherwise if upgrading is not possible, then do the following:

You try to do a normal migration on a new Linux PHP MySQL server and instead of the  default users table migration working, you get the following:

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`))
  at /home/arb/bitcoin-spread/vendor/laravel/framework/src/Illuminate/Database/Connection.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|

  Exception trace:
  1   PDOException::("SQLSTATE[42000]: Syntax error or access violation: 1071 Specified key was too long; max key length is 767 bytes")
      /home/arb/bitcoin-spread/vendor/laravel/framework/src/Illuminate/Database/Connection.php:458
  2   PDOStatement::execute()
      /home/arb/bitcoin-spread/vendor/laravel/framework/src/Illuminate/Database/Connection.php:458

  Please use the argument -v to see more details.

There is some key length incompatibility between the old MySQL database and the new one.

The solution is to add:

use Schema;

and

Schema::defaultStringLength(191);

to the AppServiceProvider boot method.

This file is in:

./app/Providers/AppServiceProvider.php

You can look for it using the command below:

find . -name "AppServiceProvider.php"

If you’ve already migrated doing ‘php artisan migrate’ is going to fail so rather do ‘php artisan migrate:fresh –seed’

Reference:
https://laravel-news.com/laravel-5-4-key-too-long-error but this is also documented in the Laravel Docs

Share this article

Leave a Reply

Your email address will not be published.

Scroll to Top