2021年5月7日金曜日

Laravel:migrationで複数テーブルの共通カラム定義を1か所に共通化する

migrationで作成日などの情報がいろいろなテーブルに定義する。

この場合、いちいち書くのは面倒であるし、間違いやすい。

共通に書く方法

macroとは、Laravelフレームワーク自体が提供しているクラスに好きなメソッドを追加することができる機能です。

例えば、

Requestクラスにユーザーエージェントを判定するメソッドを追加してみたり、

Carbonクラスに特定のフォーマットに変換するメソッドを追加してみたり、

Laravelのクラスに自由にメソッドを追加できます。


migrationで利用されているBlueprintクラスにこのmacroで機能追加することによって

共通カラムのコード共通化を行います。


Blueprintにmacro追加

Blueprintのmacroを定義するためにサービスプロバイダを新しく作ります。

makeコマンド実行。

php artisan make:provider BlueprintServiceProvider


app/Providers/BlueprintServiceProvider.php

    public function boot()
    {   // 共通カラム
        Blueprint::macro('systemColumns'function () {
            $this->boolean('isactive')
                ->comment('アクティブ区分')->default(true);            
            $this->timestamp('created_at')->comment('作成日')->nullable();
            $this->unsignedBigInteger('created_by')
                ->comment('作成ユーザ')->nullable();
            $this->timestamp('updated_at')->comment('更新日')->nullable();
            $this->unsignedBigInteger('updated_by')
                ->comment('更新ユーザ')->nullable();
            $this->timestamp('deleted_at')->comment('削除日')->nullable();
            $this->unsignedBigInteger('deleted_by')
                ->comment('削除ユーザ')->nullable();
        });
    }

config/app.php

    'providers' => [

       中略

        App\Providers\BlueprintServiceProvider::class,

    ],

migrationでmacroを利用

    public function up()
    {
        Schema::create('clients'function (Blueprint $table) {
            // base
            $table->uuid('id')->comment('id')->primary();
            $table->string('value'100)->comment('略称');
            $table->string('name'150)->comment('名前');
            $table->string('description'255)->comment('説明')->nullable();

            // 管理者:1社なら使わない


            // その他情報はinfoへ


            // 共通カラム定義
            $table->systemColumns(); 

            // 外部キー
            $table->foreign('created_by')->references('id')->on('users');
            $table->foreign('updated_by')->references('id')->on('users');
            $table->foreign('deleted_by')->references('id')->on('users');
        });
    }