LoginSignup
62
42

More than 5 years have passed since last update.

Laravel5.7: DBとしてMySQLを用意する

Last updated at Posted at 2017-10-01

ローカル開発環境で使うDBを用意します。
Laravel5.4ではSQLiteを使っていましたが、5.5からはMySQLを使うことにします。
SQLiteについては下記を御覧ください。
:link: Laravel5.4: DBとしてSQLiteを用意する - Qiita

親記事

Laravel 5.7で基本的なCRUDを作る - Qiita

MySQLのデータベースを作る

XAMPPにはphpMyAdminが付属しているので、それを使います。

  • データベース名: laravel57
  • 照合順序(Collation): utf8mb4_unicode_ci

コマンドラインでは下記のように。

PowerShell
# ユーザー名「root」、パスワードなしで接続
> mysql --user=root --password=

# 長いので改行しています。
MariaDB [(none)]> CREATE DATABASE `laravel57`
       CHARACTER SET utf8mb4
       COLLATE utf8mb4_unicode_ci;

照合順序はLaravelのデフォルトのMySQLの設定に合わせました。
:link: MySQLの文字コードとCollation - Qiita

DB設定を環境設定ファイルに記述する

.envのDB接続の部分を、先ほど作成したDBに合わせます。

.env
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel57
DB_USERNAME=root
DB_PASSWORD=

varchar型の文字数を191に制限する

MySQL5.7.7、またはMariaDB10.2.2より古い場合に必要です。
詳しくは下記を御覧ください。
:link: readouble.com: インデックス長とMySQL/MariaDB

app/Providers/AppServiceProvider.php
+ use Illuminate\Support\Facades\Schema;

(中略)

      public function boot()
      {
+         Schema::defaultStringLength(191);

マイグレーションの準備をする

:link: readouble.com: マイグレーション

users用のマイグレーション

マイグレーションのファイルは既存のものを流用します。
言語(日本語/英語)のカラムを追加します。

database/migrations/2014_10_12_000000_create_users_table.php
      public function up()
      {
          Schema::create('users', function (Blueprint $table) {
              $table->increments('id');
              $table->string('name');
              $table->string('email')->unique();
              $table->timestamp('email_verified_at')->nullable();
              $table->string('password');
+             $table->string('lang')->default('en');
              $table->rememberToken();
              $table->timestamps();
          });
      }

posts用のマイグレーション

Artisanコマンドでマイグレーションを生成します。

PowerShell
> php artisan make:migration create_posts_table

生成したファイル内のup()メソッドを下記のようにします。

database/migrations/2017_05_22_041557_create_posts_table.php
    public function up()
    {
        Schema::create('posts', function (Blueprint $table) {
            $table->increments('id');
            $table->string('title');
            $table->text('body');
            $table->timestamps();
        });
    }

テーブルの中身を用意する

:link: readouble.com: シーディング

Fakerをインストール

仮のデータを自動生成してくれるFakerを利用します。
すでにrequire-devとしてcomposer.jsonに記述されていますが、今回は本番のHerokuでも使いたいのでrequireへ移します。

composer.json
      "require": {
+         "fzaninotto/faker": "^1.4",
      },
      "require-dev": {
-         "fzaninotto/faker": "^1.4",
      },

書き換えたら、composer updateを実行します。

users用シーダー

PowerShell
# シーダーを生成
> php artisan make:seeder UsersTableSeeder

生成したファイル内のrun()メソッドを下記のリンク先のようにします。
:page_facing_up: database/seeds/UsersTableSeeder.php

posts用シーダー

PowerShell
> php artisan make:seeder PostsTableSeeder
database/seed/PostsTableSeeder.php
    public function run()
    {
        // Fakerを使う
        $faker = Faker\Factory::create('ja_JP');

        // ランダムに記事を作成
        for ($i = 0; $i < 40; $i++)
        {
            DB::table('posts')->insert([
                'title' => $faker->text(20),
                'body' => $faker->text(200),
                'created_at' => $faker->dateTime(),
                'updated_at' => $faker->dateTime(),
            ]);
        }
    }

シーダーの呼び出しを設定する

run()メソッドを下記のようにします。

database/seeds/DatabaseSeeder.php
    public function run()
    {
        $this->call([
            UsersTableSeeder::class,
            PostsTableSeeder::class,
        ]);
    }

マイグレーションとシーディングを実行する

下記を実行して、テーブルとレコードが生成されていることをphpMyAdminで確認してください。

PowerShell
# マイグレーションとシーディングを同時に行う
> php artisan migrate --seed

# 上の操作をやり直したい場合
> php artisan migrate:refresh --seed

:link: readouble.com: ロールバック

62
42
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
62
42