概要
Laravelのプロジェクト開始時の、データベースの準備・設定についてまとめる。
データベースの準備
CREATE DATABASEなどによってプロジェクトで使うデータベースを作成する。以下は新たなデータベースlaravel_test_developmentを作成した例。
| 1 2 | mysql> CREATE DATABASE laravel_test; Query OK, 1 row affected (0.01 sec) | 
.envファイルの修正
| 1 2 3 4 5 6 | DB_CONNECTION=mysql DB_HOST=127.0.0.1 DB_PORT=3306 DB_DATABASE=laravel_test←作成したデータベース名 DB_USERNAME=root DB_PASSWORD=ログインパスワード | 
データベース接続確認
php artisan migrateでマイグレーションが実行されればデータベースは正常に接続されている。
| 1 2 3 4 5 6 7 8 | [vagrant@localhost laravel_test]$ php artisan migrate Migration table created successfully. Migrating: 2014_10_12_000000_create_users_table Migrated:  2014_10_12_000000_create_users_table (0.03 seconds) Migrating: 2014_10_12_100000_create_password_resets_table Migrated:  2014_10_12_100000_create_password_resets_table (0.03 seconds) Migrating: 2019_08_19_000000_create_failed_jobs_table Migrated:  2019_08_19_000000_create_failed_jobs_table (0.01 seconds) | 
マイグレーションの結果生成されたファイル。
| 1 2 3 4 5 6 7 | [vagrant@localhost laravel_test]$ ls -al database/migrations 合計 12 drwxrwxr-x. 2 vagrant vagrant 166  5月 12 05:47 . drwxrwxr-x. 5 vagrant vagrant  72  5月 12 05:47 .. -rw-rw-r--. 1 vagrant vagrant 813  5月 12 05:47 2014_10_12_000000_create_users_table.php -rw-rw-r--. 1 vagrant vagrant 683  5月 12 05:47 2014_10_12_100000_create_password_resets_table.php -rw-rw-r--. 1 vagrant vagrant 789  5月 12 05:47 2019_08_19_000000_create_failed_jobs_table.php | 
MySQL側でもテーブルが生成されている。
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | mysql> use laravel_test Reading table information for completion of table and column names You can turn off this feature to get a quicker startup with -A Database changed mysql> show tables; +------------------------+ | Tables_in_laravel_test | +------------------------+ | failed_jobs            | | migrations             | | password_resets        | | users                  | +------------------------+ 5 rows in set (0.00 sec) | 
データベースに接続できないとき
MySQLとPHPのバージョンによっては、認証方法の違いで接続できない場合がある。その対応方法はこちら。