[Laravel] Migrationでカラムを追加する

LaravelのMigrationを使ってMySQLのテーブルにカラムを追加してみます。
テーブルを作成するときに使ったマイグレーションファイルを変更するとロールバックしたときに、テーブルが消えてしまうので、カラムの更新時には別のマイグレーションファイルを作るようにしましょう。
今回はPOST(posts)テーブルにnameというカラムを追加してみます。
初回に作成したマイグレーションファイルの確認
現在はid , body , timestamps(created_at , updated_at)が存在しています。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class CreatePostsTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('posts', function (Blueprint $table) { $table->increments('id'); $table->string('body'); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('posts'); } } |
update用ファイルの作成
1 |
$ php artisan make:migration update_posts_table --table=posts |
updateコマンドを実行すると
「/database/migrations/2020_04_15_081733_update_posts_table.php」が生成されます。
nameカラムを追加します。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class UpdatePostsTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::table('posts', function (Blueprint $table) { $table->string('name'); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::table('posts', function (Blueprint $table) { // }); } } |
ファイルを変更したらマイグレーションを実行します。
1 |
$ php artisan migrate |
最後にnameが追加されました。しかしこれだと気持ち悪いので、nameはidのすぐ後ろに追加したいところです。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class UpdatePostsTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::table('posts', function (Blueprint $table) { $table->string('name')->after('id'); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::table('posts', function (Blueprint $table) { // }); } } |
カラムを追加する時に
$table->string(‘name’)->after(‘id’);
とafterを使えば、idのすぐ後ろにnameが追加されます。
良い感じに追加されました。関連記事
- [Laravel] 7.x 認証の導入とデータベースへの接続
- [Laravel] MySQLのテーブル作成とテストデーター自動生成
- [Laravel] 利用頻度が高いコマンド一覧(artisan)
- [Laravel] インストールとMySQLの接続
- [Laravel] 公式デバッグアシスタント telescope の使い方