Laravel执行数据迁移的时候报错

Laravel Laravel 1374      收藏
[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))

laravel 5.4 改变了默认的数据库字符集,现在utf8mb4包括存储emojis支持。如果你运行MySQL v5.7.7或者更高版本,则不需要做任何事情。

当你试着在一些MariaDB或者一些老版本的的MySQL上运行 migrations 命令时,你可能会碰到下面这个错误:

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

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

自学php博客

需要找到/app/Providers/AppServiceProvider.php文件,在改文件顶部引入命名空间

use Illuminate\Support\Facades\Schema;

然后在boot方法中,加入Schema::defaultStringLength(191);设置一个默认值即可解决此问题。

代码如下:


namespace App\Providers;


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

    }


    /**

     * Register any application services.

     *

     * @return void

     */

    public function register()

    {

        //

    }

}

官网原文参考地址:https://laravel.com/docs/master/migrations#creating-indexes