LoginSignup
271
225

More than 3 years have passed since last update.

Laravel:カラムを追加する

Last updated at Posted at 2018-10-04

すでにあるテーブル(migrationファイル)にカラムを追加してphp artisan migrateしても良いが、そうするとロールバックする時に down()で テーブル自体がなくなってしまいます。

なので、新しいmigrationファイルを作って編集していきます。

① migrationファイルを作る

php artisan make:migration add_user_id_to_posts_table --table=posts

補足

既存のテーブルに変更を加える場合には、--create オプションではなく、--table オプションを使って、テーブル名を指定します。

② migrationファイルを編集

up() にはカラムの追加を、
down() はこの処理を巻き戻す処理を書きます。

add_user_id_to_posts_table.php

    public function up()
    {
        Schema::table('posts', function (Blueprint $table) {
+            $table->string('summary');  //カラム追加
        });
    }


    public function down()
    {
        Schema::table('posts', function (Blueprint $table) {
+           $table->dropColumn('summary');  //カラムの削除
        });
    }

③ migrationする

php artisan migrate

★ 確認

現在適用されているmigrationファイルの確認

php artisan migrate:status

あと、MySQLでも確認する。

DESC posts;

もしこの変更を取り消したい場合はロールバック

php artisan migrate:rollback --step=1

もしロールバックでエラーが出たら

php composer.phar dump-autoload
271
225
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
271
225