LoginSignup
1
4

More than 3 years have passed since last update.

Laravel データベース(MySQL)接続

Posted at

内容

Laradockでmysqlの設定をする際に、php artisan migrateまでは上手くいくが、その後seederを使って試しにデータベースにデータを挿入する際によくPermission denied されたので、その解決方法をメモ。

シーダーとは?

公式ドキュメントには

シーダ(初期値設定)クラスを使用し、テストデーターをデーターベースに設定するシンプルな方法もLaravelには備わっています。

このように記述されている。
要するに、お試しでデータベースにデータを挿入することと解釈。

Permission deniedの回避方法

情報収集

これが一番厄介なのでデータベースのユーザーが権限周りで拒否されない為に、ありとあらゆる権限を付与させる。参考はこちら1
権限の付与は下記mysqlコマンドで可能。

GRANT [権限] ON [適用対象のデータベース].[適用対象のテーブル] TO 'ユーザ名'@'ホスト名' IDENTIFIED BY 'パスワード';

したがって、[ ]の中身を埋めて行けば良い。
これらの情報は、laravelのプロジェクトファイルの環境設定ファイル(.env)に記載してある。

.env

DB_CONNECTION=mysql
DB_HOST=mysql
DB_PORT=3306
DB_DATABASE=database_name //[適用対象のデータベース]
DB_USERNAME=name // 'ユーザ名'
DB_PASSWORD=secret //'パスワード'

[適用対象のテーブル]は全てを対象にするので、[*]を入力。
しかし、この情報からホスト名がわからないので調べる必要がある。

docker psでworkspace_1の「CONTAINER ID」を調べ、下記コマンドを入力

docker inspect [CONTAINER ID]

そうするとかなり沢山の記述が出てくるが、下の方にある"IPAddress"の"xxx.xxx.xxx.x"をメモメモ。

MySQLを実行

ようやく材料が揃ったので、ここからはmysqlコンテナに入って権限を付与させていく。
まずはmysqlコンテナに入るところから。

docker-compose exec mysql bash

そして、rootでログインし、mysqlコマンドを実行していく。
「Enter password:」には「root」を入力。

mysql -u root -p
Enter password: 
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 4
Server version: 5.7.26 MySQL Community Server (GPL)

Copyright (c) 2000, 2019, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql> select User, Plugin from mysql.user;
+---------------+-----------------------+
| User          | Plugin                |
+---------------+-----------------------+
| root          | mysql_native_password |
| mysql.session | mysql_native_password |
| mysql.sys     | mysql_native_password |
| root          | mysql_native_password |
| name          | mysql_native_password |
+---------------+-----------------------+
5 rows in set (0.00 sec)

mysql> grant all privileges on *.* to 'name'@'IPAddress';
Query OK, 0 rows affected, 1 warning (0.01 sec)

こんな感じに表示されれば無事に権限が付与されたことになる。

シーディングを使用

いよいよ本題のシーディングだ。
ここは非常にシンプルなので、詳細はこちら参考してください。2

artisanコマンドでseederの雛形を作成。

php artisan make:seeder UsersTableSeeder

下記にテストデータを記載する。

database/seeds/UsersTableSeeder.php

<?php

use Illuminate\Database\Seeder;

class UsersTableSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        // テストデータはここに記載する。
        DB::table('users')->insert([
            'name' => 'hogemaru',
            'email' => 'hogemaru@gmail.com',
            'password' => bcrypt('hogehoge'),
        ]);
    }
}

passwordのところにbcrypt関数はパスワードをそのままデータベースに挿入するのではなく、ハッシュ値に変換して挿入する。それにより、パスワードが外部に漏れたとしても復号が困難になる為セキュリティ対策として必須の関数です。


//オートローダーを再生し、seederを実行可能にする。
composer dump-autoload

//シーダーの実行
artisan db:seed --class=UsersTableSeeder

最後にusersテーブルに保存されているか確認する。
laradockディレクトリに移動し、下記コマンドを実行。

docker-compose exec mysql bash

# mysql -u name -p

Enter password: [secret]
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 9
Server version: 5.7.26 MySQL Community Server (GPL)

Copyright (c) 2000, 2019, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql> show databases;

+--------------------+
| Database           |
+--------------------+
| information_schema |
| database_name      |
+--------------------+
2 rows in set (0.02 sec)

mysql> use database_name
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A

mysql> show tables;
+------------------------+
| Tables_in_database_dbd |
+------------------------+
| migrations             |
| password_resets        |
| users                  |
+------------------------+
3 rows in set (0.01 sec)

mysql> select * from users;
+----+------------+----------------------+-------------------+--------------------------------------------------------------+----------------+------------+------------+
| id | name       | email                | email_verified_at | password                                                     | remember_token | created_at | updated_at |
+----+------------+----------------------+-------------------+--------------------------------------------------------------+----------------+------------+------------+
|  1 | hogemaru   | hogemaru@gmail.com   | NULL              | $2y$10$iPkPapTAnhTaNdsiCw4IF.wzDjJyPQPku3dlkhGiwII3J8i11BBYy | NULL           | NULL       | NULL       |
+----+------------+----------------------+-------------------+--------------------------------------------------------------+----------------+------------+------------+
1 row in set (0.00 sec)

mysql>  exit;

これで無事に接続が可能となりました。
もし間違いがございましたらご指摘頂けますと幸いです。

参考

1
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
4