
俺はLaravelを仕事で使うことが多いから、Laravelのマイグレーションファイルの基本的な構造を解説する。
基本的な書式
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateUsersTable extends Migration
{
    public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->timestamps();
        });
    }
    public function down()
    {
        Schema::dropIfExists('users');
    }
}
重要ポイント
- テーブル名は複数形が推奨
 - カラム名は単数形で記述
 - スネークケースを使用(例:user_name)
 
カラム属性の変更
既存のカラムの属性を変更する際の書き方
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class ModifyUsersTableColumns extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('users', function (Blueprint $table) {
            $table->id(); // $table->bigIncrements(‘id’)と同じ
            $table->string('name', 50)->change(); // 'name'の長さを50文字に変更
            $table->string('email')->nullable()->change(); // 'email'をNULL許容に変更
        });
    }
    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::table('users', function (Blueprint $table) {
            $table->string('name', 255)->change(); // 元の長さに戻す(255文字)
            $table->string('email')->nullable(false)->change(); // NULL非許容に戻す
        });
    }
}
カラムの削除
カラムを削除する際の書き方
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class RemoveColumnsFromUsersTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('users', function (Blueprint $table) {
            // 単一のカラムを削除
            $table->dropColumn('name');
            // 複数のカラムを同時に削除
            $table->dropColumn(['name', 'email', 'age']);
        });
    }
    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::table('users', function (Blueprint $table) {
            // カラムを復元する場合は適切な型で追加
            $table->string('name')->nullable();
            $table->string('email')->unique()->nullable();
            $table->integer('age')->nullable();
        });
    }
}
カラムの設定:データ型
| メソッド | MYSQLの型/説明 | 範囲制限 | 使用例 | 
|---|---|---|---|
| id() | bigIncrements('id)と同じ | 0 ~ 18,446,744,073,709,551,615 | $table->increments('id'); | 
| increments() | 符号なしINT型の自動増分ID(主キー) | 0 ~ 429,4,967,295. | $table->increments('id'); | 
| bigIncrements() | 符号なしBIGINT型の自動増分ID | 0 ~ 18,446,744,073,709,551,615 | $table->bigIncrements('id'); | 
| integer() | INT型 | -2,147,483,648 ~ 2,147,483,647 | $table->integer('count'); | 
| string() | VARCHAR型 | 最大255文字(デフォルト)、長さの指定もできる | $table->string('name', 100); | 
| text() | TEXT型 | 最大16,384文字程度 | $table->text('description'); | 
| longText() | longText型 | 最大1GB程度 | $table->longText('description'); | 
| boolean() | 真偽値カラム フラグ関係のカラムに使う | $table->boolean('description'); | |
| timestamp() | TIMESTAMP型 created_at と update_at カラムを作成 | $table->timestamp('posted_at'); | |
| foreignId() | unsignedBigInteger()と同じ(←のエイリアス) | $table->foreignId(‘user_id’);; | |
| softDeletes() | ソフトデリートのためのNULL値可能な deleted_at カラム追加 | $table->softDeletes(); | 
重要ポイント
- 符号なしBIGINTとは、マイナス部分がないBIGINTということ
 - longText()はタグなども含む文章や画像をbase64エンコードしてhtmlテキストの中に埋め込むような時に使える
 - idカラムはid()を使う
 
カラムの設定:オプション
| メソッド | 説明 | 使用例 | 
|---|---|---|
| nullable() | NULL値を許可 | $table->string('middle_name')->nullable(); | 
| default() | デフォルト値を設定 | $table->boolean('is_active')->default(true); | 
| unsigned() | 符号なし(unsigned)属性を付与 | $table->integer('user_id')->unsigned(); | 
| comment() | カラムにコメントを追加 | $table->string('api_key')->comment('APIキー'); | 
カラムの設定:インデックス
| メソッド | 説明 | 使用例 | 
|---|---|---|
| unique() | ユニークキーを追加 | $table->string('email')->unique(); | 
| index() | インデックスを追加 | $table->integer('category_id')->index(); | 
| primary() | プライマリーキーを設定 | $table->primary(['id', 'type']); | 
外部キーの作成
// usersテーブルの作成
Schema::create('users', function (Blueprint $table) {
    $table->id(); // 符号なしBIGINT型
    $table->string('name');
    $table->timestamps();
    $table->softDeletes();
});
// rolesテーブルの作成(外部キー制約あり)
Schema::create('roles', function (Blueprint $table) {
    $table->id();
    $table->foreignId('user_id'); 
    $table->string('role_name');
    $table->timestamps();
    // 外部キー制約の追加
    $table->foreign('user_id')
          ->references('id')
          ->on('users');
});
重要ポイント
- usersテーブルとrolesテーブルには外部キー制約が設定されている
 - 具体的に、rolesテーブルのuser_idカラムはusersテーブルのidカラムを参照している
 - 外部キーとして参照されるカラムは、同じデータ型と属性を持つ必要がある(なのでリレーションでusersのidを入れたuser_idカラムを作るときには注意)
 
実例
ブログ記事テーブルの作成例:
Schema::create('users', function (Blueprint $table) {
    $table->id('id')->comment('ID');
    $table->string('family_name', 40);->comment('性');
    $table->string('first_name', 40);->comment('名');
    $table->string('email')->unique()->comment('メールアドレス');
    $table->timestamp('email_verified_at')->nullable();
    $table->string('password')->comment('パスワード');
    $table->rememberToken();
    $table->timestamps();
  $table->softDeletes()->comment('削除or退会日時ornull 日付が入ると削除したことになる');
});
Schema::create('posts', function (Blueprint $table) {
    $table->increments('id');
    $table->unsignedInteger('user_id');
    $table->string('title');
    $table->text('content');
    $table->boolean('is_published')->default(false);
    $table->timestamps();
    $table->foreign('user_id')
          ->references('id')
          ->on('users');
});
以上がLaravelにおけるマイグレーションファイルの基本と実践的な使用方法の解説。データベース設計時の参考にしてほしい。