LaravelからMySQL8へ接続時のエラー

投稿者: | 2020年11月9日

現象

php artisan migrate を実行したところ、下記のようなエラーが表示されました。

   Illuminate\Database\QueryException

  SQLSTATE[HY000] [2054] The server requested authentication method unknown to the client (SQL: select * from information_schema.tables where table_schema = tokyo_cci and table_name = migrations and table_type = 'BASE TABLE')

  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|

      +33 vendor frames
  34  artisan:37
      Illuminate\Foundation\Console\Kernel::handle(Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))

原因

MySQLの認証方式が8より変わっているため。

対処方法

接続ユーザーを作成するときのパスワードの設定を次のように「mysql_native_password」を使うように修正。これで接続できるようになりました。

ALTER USER 'user1'@'localhost' IDENTIFIED WITH mysql_native_password BY '(パスワード)';