LoginSignup
1
2

More than 3 years have passed since last update.

Laravel:既存テーブルにカラムを追加する方法

Posted at

概要

Laravelで既存テーブルにカラムを追加する方法について解説

image.png

手順1:追加用のマイグレーションを作成

ターミナルで下記のようにコマンドを実行する


//コマンド形式
$ php artisan make:migration add_カラム名_to_テーブル名_table --table=テーブル名

//例1 memosテーブルにtitleカラムを追加する場合
$ php artisan make:migration add_title_to_memos_table --table=memos

//例2 アンダーバーがあるuser_idカラムなどを追加する場合
$ php artisan make:migration add_user_id_to_memos_table --table=memos

手順2:作成したマイグレーションファイルを編集

アプリ名/database/migrations配下に先ほど作ったファイルが作成されているので
function up の部分に追加したいカラムを下記のように記述を行う(今回の場合titleカラム)


<?php

    public function up()
    {
            //
    }

↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓

    public function up()
    {
        Schema::table('memos', function (Blueprint $table) {
            $table->string('title');
        });
    }

手順3:マイグレーションコマンドを実行

下記のコマンドを実行

$ php artisan migrate

手順4:DBを確認してカラムが追加されているか確認

image.png

カラムが追加されていてば完了となります。

1
2
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
1
2