0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Laravelでマイグレーションを使ってテーブルにカラムを追加する

Last updated at Posted at 2021-09-12

はじめに#

 phpmyadminを使えばカラムを追加するのは簡単ですが、Laravelにはマイグレーションファイルがあります。マイグレーションファイルを使ったカラムの追加方法を備忘録として残していきます。

追加手順#

 まずは新たにマイグレーションファイルを作成します。今回はitemsテーブルにimageカラムを追加するという想定でいきましょう。

 php artisan make:migration add_image_to_items_table --table=items

ターミナルでこのように打ちこむと、新しくマイグレーションファイルが生成されます。
public function up()にカラムの追加の記述を入れましょう。downの方には削除の記述をしておきます。

xxxx_add_image_to_items_table.php
class AddImageToItemsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('items', function (Blueprint $table) {
            //
            $table->string('image');  //カラム追加
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::table('items', function (Blueprint $table) {
            //
            $table->dropColumn('image');  //カラムの削除
        });
    }
}

マイグレーションファイルの編集が終わったら実行しましょう。

 php artisan migrate

無事にitemsテーブルにimageカラムを追加することが出来ました!

0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?