LoginSignup
1
0

More than 1 year has passed since last update.

Laravelのカラム追加方法

Posted at

既にテーブルは構築済みであり、後から機能の追加に伴いテーブルのカラムも追加する必要が出てきたたとします。

今回、筆者が行った方法について紹介させていただきます。

追加migrationファイルの作成

php artisan make:migration add_article_to_users_table --table=users

usersテーブルにarticleというカラムを追加する為、上記artisanコマンドを実施。

migrationのフォルダ内に『2022_01_12_140902_add_article_to_users_table.php』というファイルが作成されます。

2022_01_12_140902_add_article_to_users_table.php
<?php

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

class AddArticleToUsersTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('users', function (Blueprint $table) {
        //{{ ここに追加したいカラム情報を記入 }}
        });
    }

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

追加したいカラム情報の反映

UP()の中に追加したいカラム情報を記載します。
例)↓

2022_01_12_140902_add_article_to_users_table.php
    public function up()
    {
        Schema::table('users', function (Blueprint $table) {
        $table->string('article',400)->nullable();
        });
    }

『$table->string('article',400)->nullable();』というカラム情報を追加したい場合は上記記載となります。

php artisan migrate

追加したカラム情報が一通り記載終えたら、
最期に上記artisanコマンドを実施。
以上となります。

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