LoginSignup
19
13

More than 3 years have passed since last update.

Laravel8 Migration 無名クラスの書き方をサポート

Last updated at Posted at 2021-04-19

Laravel8.37から新しく無名マイグレーションの書き方がサポートされるようになりました。
Laravel9以降はこの書き方がデフォルトになると思われます。

対応Laravelバージョン

通常のマイグレーションの書き方

database/migrations/2021_04_20_000000_create_tasks_table.php
<?php

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

class CreateTasksTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('tasks', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('tasks');
    }
}

無名クラスのマイグレーションの書き方

database/migrations/2021_04_20_000000_create_tasks_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.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('tasks', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('tasks');
    }
};

変更箇所

変わる部分はここだけです。

// old
class CreateTasksTable extends Migration

// new
return new class extends Migration

現時点では新旧どちらの書き方もサポートされているのでご安心ください。

メリット

  • クラス名の部分が無名クラスになることで、クラス名の競合問題を気にしなくて良くなります。
    • マイグレーションファイルさえ一意であればok
  • マイグレーションファイル名を変更したいときにクラス名を修正する手間がなくなります。

(同じ名前のマイグレーションファイル書くんか...ってのはありますが...)

make:migration

$ php artisan make:migration create_tasks_table

執筆時点(2021/4/20)では古い書き方のコードが生成されます。
今後新しいテンプレートになると思われます。

スタブのカスタマイズ

新しい書き方に合わせたい場合は、スタブを変更できます。

$ php artisan stub:publish

stub ディレクトリが生成されます。

stubs/migration.create.stub
stubs/migration.stub
stubs/migration.update.stub

この3ファイルのクラス名の定義部分を下記のコードに書き換えればokです!

return new class extends Migration

末尾のクラスの閉じ括弧に ; を付ける。

};

参考

19
13
2

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
19
13