LoginSignup
0
0

【Laravel migration】テーブルの編集2(カラムの編集)

Posted at

Laravelのマイグレーション

データベースの作成や編集、削除などを管理する方法として、PHPフレームワークのLaravelには「マイグレーション」というものが備わっています。
本記事では、マイグレーションで生成されたテーブルを編集する方法(カラムの編集)について書きます。

カラムの追加・削除については、下の記事をご参照ください。

開発環境

XAMPP
MySQL 5.2
Laravel 10.1
php 8.1

1. カラムの編集の前に

カラムの編集を行う場合、Composerパッケージマネージャを使い、doctrine/dbalパッケージをインストールする必要があります。
コマンドは以下の通り。

composer require doctrine/dbal

2. マイグレーションファイルの作成

カラムを編集するマイグレーションファイルを作成します。
下の例では、既存postsテーブルの既存titleカラムを編集しようとしています。

$ php artisan make:migration change_title_of_posts_table

database/migrationsディレクトリ内に以下のマイグレーションファイルが生成されます。

2023_06_08_131653_change_title_of_posts_table.php
<?php

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

return new class extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        //
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        //
    }
};

新しく生成されたマイグレーションファイルの「up」に変更の内容、「down」に変更を基に戻す内容をそれぞれ挿入します。なぜかSchemaも生成されていないので、Schemaも書きます。
下の図ではtitleカラムをnullableに変更しています。downはnullable(false)にしてあげればOKです。
最後のchengeを忘れないこと。

2023_06_08_131653_change_title_of_posts_table.php
<?php

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

return new class extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        Schema::table('posts', function (Blueprint $table) {
            $table->string('title')->nullable(true)->change();
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::table('posts', function (Blueprint $table) {
            $table->string('title')->nullable(false)->change();
        });
    }
};

最後にマイグレーションを実行すれば、カラムの編集完了です。

php artisan migrate
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