2
0

More than 3 years have passed since last update.

Laravelを調べる:初めてのmigrate編

Posted at

Laravelを調べる:初めてのmigrate編

編集中です!!

モデルの確認

Laravelを調べる:Docker起動編 での展開直後、Models/User.phpがすでに存在していた。

私は慌ててmigrate(後述)してしまい、フィールドを追加し忘れてしまったので、ここは一旦落ち着いて見直すのがよいと思う。

app
...
├── Models
│   └── User.php
...
% tree database
database
├── factories
│   └── UserFactory.php
├── migrations
│   ├── 2014_10_12_000000_create_users_table.php <============これー
│   ├── 2014_10_12_100000_create_password_resets_table.php
│   └── 2019_08_19_000000_create_failed_jobs_table.php
└── seeders
    └── DatabaseSeeder.php

migrationファイル ( 2014_10_12_000000_create_users_table.php )

開発初期段階で必要なフィールドはここを変更することで対応するのでよさそう。(Laravelの定石的なところは未確認)

また、web applicationのバージョンアップでフィールドの追加が必要になった場合には、このファイルはそのままで、別途migrationファイルを追加するのが手順のよう。

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateUsersTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->string('email')->unique();
            $table->timestamp('email_verified_at')->nullable();
            $table->string('password');
            $table->rememberToken();
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('users');
    }
}

sailコマンドによるmigrate

【コマンド】

$ ./vendor/bin/sail artisan migrate

【実行結果】

$ ./vendor/bin/sail artisan migrate
Migration table created successfully.
Migrating: 2014_10_12_000000_create_users_table
Migrated:  2014_10_12_000000_create_users_table (53.22ms)
Migrating: 2014_10_12_100000_create_password_resets_table
Migrated:  2014_10_12_100000_create_password_resets_table (37.86ms)
Migrating: 2019_08_19_000000_create_failed_jobs_table
Migrated:  2019_08_19_000000_create_failed_jobs_table (38.45ms)

データベースを確認してみる。

$ ./vendor/bin/sail mysql
mysql> show databases;
+--------------------+
| Database           |
+--------------------+
| example_app        |
| information_schema |
+--------------------+
mysql> use example_app;
Database changed
mysql> show tables;
+-----------------------+
| Tables_in_example_app |
+-----------------------+
| failed_jobs           |
| migrations            |
| password_resets       |
| users                 |
+-----------------------+
4 rows in set (0.00 sec)
2
0
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
2
0