【Laravel】migrationでテーブルにカラムを追加・更新する

  • 2021年7月2日
  • 2022年2月5日
  • Laravel, PHP
  • 3144view

今回はLaravel(バージョン8~)のmigrationを用いて、既存のDBテーブルにカラムを追加・更新する方法を解説していきます。

流れ

  1. 更新用のmigrationフォルダを作る
  2. migrationフォルダに変更したいカラムの処理を書く
  3. php artisan migrateで反映

1 更新用のmigrationフォルダを作る

artisanコマンドでmigrationファイルを作ります。

php artisan migration テーブル名 --table=テーブル名

既存のテーブルに変更を加える場合は--table=テーブル名で既存のテーブル名を指定。
migrationファイルのテーブル名も具体的な方が良いです。

例)

php artisan make:migration add_user_id_to_lecture_table --table=lecture

2 migrationフォルダに変更したいカラムの処理を書く

カラムを追加する場合

例)

Schema::table('users', function (Blueprint $table) {
 $table->string('email');  //カラム追加
});

既存のカラムを変更する場合

既存のカラムを変更する場合はchange()を使います。

公式

例)

 
//name列のサイズ変更
Schema::table('users', function (Blueprint $table) {
    $table->string('name', 50)->change();
});
        
        
//nameをnull許容に変更
Schema::table('users', function (Blueprint $table) {
    $table->string('name', 50)->nullable()->change();
});
    

3 php artisan migrate

最後にphp artisan migrateしましょう。
DBを確認して反映されていたらOKです。

参考

https://qiita.com/usaginooheso/items/6f307a15b5f7d5dd981f

https://pgmemo.tokyo/data/archives/1545.html

Select the fields to be shown. Others will be hidden. Drag and drop to rearrange the order.
  • Image
  • SKU
  • Rating
  • Price
  • Stock
  • Availability
  • Add to cart
  • Description
  • Content
  • Weight
  • Dimensions
  • Additional information
  • Attributes
  • Custom attributes
  • Custom fields
Click outside to hide the compare bar
Compare
Compare ×
Let's Compare! Continue shopping