LoginSignup
31
29

More than 5 years have passed since last update.

Laravel5のお勉強 -第三回 Database連携-

Last updated at Posted at 2015-10-12

Laravel5のお勉強

第一回 環境構築
第二回 ControllerとViewの追加
第三回 Database連携(Mysql)
第四回 モデルの作成/tinker紹介
第五回 テストデータの挿入/Fakerの使用
第六回 CRUDの作成
第七回 Herokuにdeploy

第三回 Database連携-

前提条件

Mac OS yosemite
PHP 5.5以上
Mysql 5.6以上

目的

Laravel5のお勉強。
ここが公式の日本語翻訳サイト

今回はLaravelでDatabase連携する方法について学ぶ

DB環境設定

PJのルートで「ls -ltra」で隠しファイルも表示してみよう。

$ cat -n .env
     1  APP_ENV=local
     2  APP_DEBUG=true
     3  APP_KEY=xxxxxxxxxxx
     4  
     5  DB_HOST=localhost
     6  DB_DATABASE=test
     7  DB_USERNAME=root
     8  DB_PASSWORD=root
     9  
    10  CACHE_DRIVER=file
    11  SESSION_DRIVER=file
    12  QUEUE_DRIVER=sync
    13  
    14  MAIL_DRIVER=smtp
    15  MAIL_HOST=mailtrap.io
    16  MAIL_PORT=2525
    17  MAIL_USERNAME=null
    18  MAIL_PASSWORD=null
    19  MAIL_ENCRYPTION=null

ここにDB周りの設定を記述する。
今回は私はlocalhostのtestデータベースにユーザーをrootでpassをrootで接続しにいくよ。local開発環境で。って記述になります。
.env は開発環境やステージング環境、本番環境などで、環境毎に変更したい情報をまとめておくファイルです。
そして、データベースに関する設定記述は、

$pwd(Blog)
$cd ./config
$tree
config
├── app.php
├── auth.php
├── broadcasting.php
├── cache.php
├── compile.php
├── database.php
├── database.php.org
├── filesystems.php
├── mail.php
├── queue.php
├── services.php
├── session.php
└── view.php

config下にdatabase.phpがあるので、ここに記述します。

$ cat -n database.php
     1  <?php
     2  return [
     3      'fetch' => PDO::FETCH_CLASS,
     4      'default' => env('DB_CONNECTION', 'mysql'),
     5      'connections' => [
     6          'mysql' => [
     7              'driver'    => 'mysql',
     8              'host'      => env('DB_HOST', 'localhost'),
     9              'unix_socket'   => '/private/tmp/mysql.sock',
    10              'database'  => env('DB_DATABASE', 'test'),
    11              'username'  => env('DB_USERNAME', 'root'),
    12              'password'  => env('DB_PASSWORD', 'root'),
    13              'charset'   => 'utf8',
    14              'collation' => 'utf8_unicode_ci',
    15              'prefix'    => '',
    16              'strict'    => false,
    17          ],
    18      ],
    19      'migrations' => 'migrations',
    20      'redis' => [
    21          'cluster' => false,
    22          'default' => [
    23              'host'     => '127.0.0.1',
    24              'port'     => 6379,
    25              'database' => 0,
    26          ],
    27      ],
    28  ];

今回はMysqlしか使わないので、見易さ重視で他の不要な記述を削除した上で掲載してます。
デフォルトではpostgresだったり、sqlsrvだったり、sqliteだったりと、いろいろなDBの記載があると思います。
使いたいDBに合わせて読み替えてください。

'database'  => env('DB_DATABASE', 'test')

この記述は「.envの「DB_DATABASE」から取得した値を設定。ただしない場合はデフォルトで「test」を指定するよ」って記載になってます。

これで設定は完了です。

マイグレーションファイルの作成

DBの接続設定は完了したので、次は実際につなぎにいくテーブルの作成や削除等、マイグレーションの作成を行っていきます。

  • マイグレーションとは…データベースのバージョンを管理すること

今回は適当にBlogを綴っていくサンプルアプリなので、以下のコマンドの

php artisan make:migration 【マイグレーションファイル名】

【マイグレーションファイル名】に「何を・どのテーブルに・どうするか」を書きます。
※マイグレーションファイルは artisan make:migration コマンドで作成します。

なので、とりあえず以下にしましょう。

php artisan make:migration create_articles_table

→「articlesテーブルを作成する」コマンドを発行します。

このコマンドを発行すると、migrationファイルが以下に作成されます。

$ pwd(Blog)
$ cd database
$ tree
database
├── factories
│   └── ModelFactory.php
├── migrations
│   ├── 2014_10_12_000000_create_users_table.php
│   ├── 2014_10_12_100000_create_password_resets_table.php
│   └── 2015_10_10_154228_create_articles_table.php
└── seeds
    └── DatabaseSeeder.php

2014年系のファイルはデフォルトで用意されるmigrationファイルです。
Laravel5からは、デフォルトでUserテーブルとpasswordテーブルが作成されるようになりました。
自分で作成したのはarticleテーブルなので、ここで見て欲しいのは「2015_10_10_154228_create_articles_table.php」となります。

では中身を見てみましょう。

$ cat -n 2015_10_10_154228_create_articles_table.php 
     1  <?php
     2  
     3  use Illuminate\Database\Schema\Blueprint;
     4  use Illuminate\Database\Migrations\Migration;
     5  
     6  class CreateArticlesTable extends Migration
     7  {
     8      /**
     9       * Run the migrations.
    10       *
    11       * @return void
    12       */
    13      public function up()
    14      {
    15          Schema::create('articles', function(Blueprint $table) {
    16              $table->increments('id');
    17              $table->string('title');
    18              $table->text('body');
    19              $table->timestamps();
    20          });
    21      }
    22  
    23      /**
    24       * Reverse the migrations.
    25       *
    26       * @return void
    27       */
    28      public function down()
    29      {
    30          Schema::drop('articles');
    31      }
    32  }

upメソッドがmigrationが初めて実行された時に走る処理となっており、downがmigrationコマンドのrollbackが実行された時に評価されます。
migrationの実行はmigrationテーブルの中で、migrationファイルごとにversion管理されてます。
ここで「migration」コマンドや、「migration:rollback」されたかどうかを管理しています。

まだmigrationファイルが作成されただけであり、テーブル自体は作成されてません。
では次に

$ php artisan migrate

このコマンドを打ちます。するとMysqlにcreate_articles_table.phpに記載されたmigration記述(テーブル定義)が流し込まれ、create table文が実行されます。

mySQLに入り、以下で確認してみよう。

$ mysql -u root -proot
$ use test;
$ show tables;
mysql> show tables;
+-----------------+
| Tables_in_test  |
+-----------------+
| articles        |
| migrations      |
| password_resets |
| users           |
+-----------------+
$ select * from migrations;
mysql> select * from migrations;
+------------------------------------------------------+-------+
| migration                                            | batch |
+------------------------------------------------------+-------+
| 2014_10_12_000000_create_users_table                 |     1 |
| 2014_10_12_100000_create_password_resets_table       |     1 |
| 2015_10_10_154228_create_articles_table              |     1 |
+------------------------------------------------------+-------+
mysql> desc articles;
+--------------+------------------+------+-----+---------------------+----------------+
| Field        | Type             | Null | Key | Default             | Extra          |
+--------------+------------------+------+-----+---------------------+----------------+
| id           | int(10) unsigned | NO   | PRI | NULL                | auto_increment |
| title        | varchar(255)     | NO   |     | NULL                |                |
| body         | text             | NO   |     | NULL                |                |
| created_at   | timestamp        | NO   |     | 0000-00-00 00:00:00 |                |
| updated_at   | timestamp        | NO   |     | 0000-00-00 00:00:00 |                | |
+--------------+------------------+------+-----+---------------------+----------------+

こんな感じですね。

見事、Laravel上で作成したテーブル定義でMysqlに実際にテーブルが作成されました。

テーブル定義の途中変更

先ほど作成したarticleテーブルにpublished_atカラムを追加します。

php artisan make:migration add_published_at_to_articles_table --table=articles

新しいmigrationファイルが作成されます。

※2015_10_11_091650_add_published_at_to_articles_table.php
$ cat -n 2015_10_11_091650_add_published_at_to_articles_table.php 
     1  <?php
     2  
     3  use Illuminate\Database\Schema\Blueprint;
     4  use Illuminate\Database\Migrations\Migration;
     5  
     6  class AddPublishedAtToArticlesTable extends Migration
     7  {
     8      /**
     9       * Run the migrations.
    10       *
    11       * @return void
    12       */
    13      public function up()
    14      {
    15          Schema::table('articles', function (Blueprint $table) {
    16              $table->timestamp('published_at')->nullable();
    17          });
    18      }
    19  
    20      /**
    21       * Reverse the migrations.
    22       *
    23       * @return void
    24       */
    25      public function down()
    26      {
    27          Schema::table('articles', function (Blueprint $table) {
    28              $table->dropColumn('published_at');
    29          });
    30      }
    31  }

runで、timestamp型の「published_at」を追加するよう、記載されてます。
では

$ php artisan migrate

で実行するとMysqlに流し込まれます。
mysqlにloginしてみてみよう。

mysql> desc articles;
+--------------+------------------+------+-----+---------------------+----------------+
| Field        | Type             | Null | Key | Default             | Extra          |
+--------------+------------------+------+-----+---------------------+----------------+
| id           | int(10) unsigned | NO   | PRI | NULL                | auto_increment |
| title        | varchar(255)     | NO   |     | NULL                |                |
| body         | text             | NO   |     | NULL                |                |
| created_at   | timestamp        | NO   |     | 0000-00-00 00:00:00 |                |
| updated_at   | timestamp        | NO   |     | 0000-00-00 00:00:00 |                |
| published_at | timestamp        | YES  |     | NULL                |                |
+--------------+------------------+------+-----+---------------------+----------------+

以上です。

31
29
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
31
29