Readouble

Laravel 8.x マイグレーション

イントロダクションIntroduction

マイグレーションはデータベースのバージョン管理のようなもので、チームがアプリケーションのデータベーススキーマを定義および共有できるようにします。ソース管理から変更を取得した後に、ローカルデータベーススキーマにカラムを手動で追加するようにチームメートに指示する必要があったことを経験していれば、データベースのマイグレーションにより解決される問題に直面していたのです。Migrations are like version control for your database, allowing your team to define and share the application's database schema definition. If you have ever had to tell a teammate to manually add a column to their local database schema after pulling in your changes from source control, you've faced the problem that database migrations solve.

LaravelのSchemaファサードは、Laravelがサポートするすべてのデータベースシステムに対し、テーブルを作成、操作するために特定のデータベースに依存しないサポートを提供します。通常、マイグレーションはこのファサードを使用して、データベースのテーブルとカラムを作成および変更します。The Laravel Schema facade[/docs/{{version}}/facades] provides database agnostic support for creating and manipulating tables across all of Laravel's supported database systems. Typically, migrations will use this facade to create and modify database tables and columns.

マイグレーションの生成Generating Migrations

make:migration Artisanコマンドを使用して、データベースマイグレーションを生成します。新しいマイグレーションは、database/migrationsディレクトリに配置されます。各マイグレーションファイル名には、Laravelがマイグレーションの順序を決定できるようにするタイムスタンプを含めています。You may use the make:migration Artisan command[/docs/{{version}}/artisan] to generate a database migration. The new migration will be placed in your database/migrations directory. Each migration filename contains a timestamp that allows Laravel to determine the order of the migrations:

php artisan make:migration create_flights_table

Laravelは、マイグレーションの名前からテーブル名と新しいテーブルを作成しようとしているかを推測しようとします。Laravelがマイグレーション名からテーブル名を決定できる場合、Laravelは生成するマイグレーションファイルへ指定したテーブル名を事前に埋め込みます。それ以外の場合は、マイグレーションファイルのテーブルを手動で指定してください。Laravel will use the name of the migration to attempt to guess the name of the table and whether or not the migration will be creating a new table. If Laravel is able to determine the table name from the migration name, Laravel will pre-fill the generated migration file with the specified table. Otherwise, you may simply specify the table in the migration file manually.

生成するマイグレーションのカスタムパスを指定する場合は、make:migrationコマンドを実行するときに--pathオプションを使用します。指定したパスは、アプリケーションのベースパスを基準にする必要があります。If you would like to specify a custom path for the generated migration, you may use the --path option when executing the make:migration command. The given path should be relative to your application's base path.

lightbulb">Tip!! マイグレーションのスタブはスタブのリソース公開を使用してカスタマイズできます。{tip} Migration stubs may be customized using stub publishing[/docs/{{version}}/artisan#stub-customization].

マイグレーションの圧縮Squashing Migrations

アプリケーションを構築していくにつれ、時間の経過とともに段々と多くのマイグレーションが蓄積されていく可能性があります。これにより、database/migrationsディレクトリが数百のマイグレーションで肥大化する可能性があります。必要に応じて、マイグレーションを単一のSQLファイルに「圧縮」できます。利用するには、schema:dumpコマンドを実行します。As you build your application, you may accumulate more and more migrations over time. This can lead to your database/migrations directory becoming bloated with potentially hundreds of migrations. If you would like, you may "squash" your migrations into a single SQL file. To get started, execute the schema:dump command:

php artisan schema:dump

// 現在のデータベーススキーマをダンプし、既存のすべての移行を削除
php artisan schema:dump --prune

このコマンドを実行すると、Laravelは「スキーマ」ファイルをアプリケーションのdatabase/schemaディレクトリに書き込みます。これ以降、データベースをマイグレーションするときに、まだ他のマイグレーションが実行されていない場合、Laravelは最初にスキーマファイルのSQLステートメントを実行します。スキーマファイルのステートメントを実行した後、Laravelはスキーマダンプのに入っていない残りのマイグレーションを実行します。When you execute this command, Laravel will write a "schema" file to your application's database/schema directory. Now, when you attempt to migrate your database and no other migrations have been executed, Laravel will execute the schema file's SQL statements first. After executing the schema file's statements, Laravel will execute any remaining migrations that were not part of the schema dump.

チームの新しい開発者がアプリケーションの初期データベース構造をすばやく作成できるようにするため、データベーススキーマファイルはソース管理にコミットすべきでしょう。You should commit your database schema file to source control so that other new developers on your team may quickly create your application's initial database structure.

Note: note マイグレーションの圧縮は、MySQL、PostgreSQL、SQLiteデータベースでのみ利用可能で、データベースのコマンドラインクライアントを利用しています。スキーマダンプは、メモリ内SQLiteデータベースへ復元されない場合があります。{note} Migration squashing is only available for the MySQL, PostgreSQL, and SQLite databases and utilizes the database's command-line client. Schema dumps may not be restored to in-memory SQLite databases.

マイグレーションの構造Migration Structure

移行クラスには、updownの2つのメソッドを用意します。upメソッドはデータベースに新しいテーブル、カラム、またはインデックスを追加するために使用します。downメソッドでは、upメソッドによって実行する操作を逆にし、以前の状態へ戻す必要があります。A migration class contains two methods: up and down. The up method is used to add new tables, columns, or indexes to your database, while the down method should reverse the operations performed by the up method.

これらの両方のメソッド内で、Laravelスキーマビルダを使用して、テーブルを明示的に作成および変更できます。Schemaビルダで利用可能なすべてのメソッドを学ぶには、ドキュメントをチェックしてください。たとえば、次のマイグレーションでは、flightsテーブルが作成されます。Within both of these methods, you may use the Laravel schema builder to expressively create and modify tables. To learn about all of the methods available on the Schema builder, check out its documentation[#creating-tables]. For example, the following migration creates a flights table:

<?php

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

class CreateFlightsTable extends Migration
{
    /**
     * マイグレーションの実行
     *
     * @return void
     */
    public function up()
    {
        Schema::create('flights', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->string('airline');
            $table->timestamps();
        });
    }

    /**
     * マイグレーションを戻す
     *
     * @return void
     */
    public function down()
    {
        Schema::drop('flights');
    }
}

無名マイグレーションAnonymous Migrations

上記の例で気付いたかもしれませんが、Laravelはmake:migrationコマンドで生成した全てのマイグレーションへ自動的にクラス名を割り当てます。しかし、必要であれば、マイグレーションファイルから無名のクラスを返すこともできます。これは主に、アプリケーションが多くのマイグレーションを蓄積し、そのうち2つのマイグレーションでクラス名が衝突している場合に便利です。As you may have noticed in the example above, Laravel will automatically assign a class name to all of the migrations that you generate using the make:migration command. However, if you wish, you may return an anonymous class from your migration file. This is primarily useful if your application accumulates many migrations and two of them have a class name collision:

<?php

use Illuminate\Database\Migrations\Migration;

return new class extends Migration
{
    //
};

マイグレーション接続の設定Setting The Migration Connection

マイグレーションがアプリケーションのデフォルトのデータベース接続以外のデータベース接続を操作する場合は、マイグレーションの$connectionプロパティを設定する必要があります。If your migration will be interacting with a database connection other than your application's default database connection, you should set the $connection property of your migration:

/**
 * マイグレーションが使用するデータベース接続
 *
 * @var string
 */
protected $connection = 'pgsql';

/**
 * マイグレーションの実行
 *
 * @return void
 */
public function up()
{
    //
}

マイグレーションの実行Running Migrations

未処理のマイグレーションをすべて実行するには、migrate Artisanコマンドを実行します。To run all of your outstanding migrations, execute the migrate Artisan command:

php artisan migrate

これまでどのマイグレーションが実行されているかを確認したい場合は、migrate:status Artisanコマンドを使用してください。If you would like to see which migrations have run thus far, you may use the migrate:status Artisan command:

php artisan migrate:status

マイグレーションを強制的に本番環境で実行するForcing Migrations To Run In Production

一部のマイグレーション操作は破壊的です。つまり、データーが失われる可能性を持っています。本番データベースに対してこれらのコマンドを実行しないように保護するために、コマンドを実行する前に確認を求めるプロンプトが表示されます。プロンプトなしでコマンドを強制的に実行するには、--forceフラグを使用します。Some migration operations are destructive, which means they may cause you to lose data. In order to protect you from running these commands against your production database, you will be prompted for confirmation before the commands are executed. To force the commands to run without a prompt, use the --force flag:

php artisan migrate --force

マイグレーションのロールバックRolling Back Migrations

最新のマイグレーション操作をロールバックするには、rollback Artisanコマンドを使用します。このコマンドは、マイグレーションの最後の「バッチ」をロールバックします。これは、複数のマイグレーションファイルを含む場合があります。To roll back the latest migration operation, you may use the rollback Artisan command. This command rolls back the last "batch" of migrations, which may include multiple migration files:

php artisan migrate:rollback

rollbackコマンドにstepオプションを提供することにより、限られた数のマイグレーションをロールバックできます。たとえば、次のコマンドは最後の5つのマイグレーションをロールバックします。You may roll back a limited number of migrations by providing the step option to the rollback command. For example, the following command will roll back the last five migrations:

php artisan migrate:rollback --step=5

migrate:resetコマンドは、アプリケーションのすべてのマイグレーションをロールバックします。The migrate:reset command will roll back all of your application's migrations:

php artisan migrate:reset

単一コマンドでロールバックとマイグレーション実行Roll Back & Migrate Using A Single Command

migrate:refreshコマンドは、すべてのマイグレーションをロールバックしてから、migrateコマンドを実行します。このコマンドは、データベース全体を効果的に再作成します。The migrate:refresh command will roll back all of your migrations and then execute the migrate command. This command effectively re-creates your entire database:

php artisan migrate:refresh

// データベースを更新し、すべてのデータベース初期値設定を実行
php artisan migrate:refresh --seed

refreshコマンドにstepオプションを指定し、特定の数のマイグレーションをロールバックしてから再マイグレーションできます。たとえば、次のコマンドは、最後の5マイグレーションをロールバックして再マイグレーションします。You may roll back and re-migrate a limited number of migrations by providing the step option to the refresh command. For example, the following command will roll back and re-migrate the last five migrations:

php artisan migrate:refresh --step=5

すべてのテーブルを削除後にマイグレーションDrop All Tables & Migrate

migrate:freshコマンドは、データベースからすべてのテーブルを削除したあと、migrateコマンドを実行します。The migrate:fresh command will drop all tables from the database and then execute the migrate command:

php artisan migrate:fresh

php artisan migrate:fresh --seed

Note: note migrate:freshコマンドは、プレフィックスに関係なく、すべてのデータベーステーブルを削除します。このコマンドは、他のアプリケーションと共有されているデータベースで開発している場合は注意して使用する必要があります。{note} The migrate:fresh command will drop all database tables regardless of their prefix. This command should be used with caution when developing on a database that is shared with other applications.

テーブルTables

テーブルの生成Creating Tables

新しいデータベーステーブルを作成するには、Schemaファサードでcreateメソッドを使用します。createメソッドは2つの引数を取ります。1つ目はテーブルの名前で、2つ目は新しいテーブルを定義するために使用できるBlueprintオブジェクトを受け取るクロージャです。To create a new database table, use the create method on the Schema facade. The create method accepts two arguments: the first is the name of the table, while the second is a closure which receives a Blueprint object that may be used to define the new table:

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

Schema::create('users', function (Blueprint $table) {
    $table->id();
    $table->string('name');
    $table->string('email');
    $table->timestamps();
});

テーブルを作成するときは、スキーマビルダのカラムメソッドのいずれかを使用して、テーブルのカラムを定義します。When creating the table, you may use any of the schema builder's column methods[#creating-columns] to define the table's columns.

テーブル/カラムの存在の確認Checking For Table / Column Existence

hasTableおよびhasColumnメソッドを使用して、テーブルまたは列の存在を確認できます。You may check for the existence of a table or column using the hasTable and hasColumn methods:

if (Schema::hasTable('users')) {
    // "users"テーブルは存在していた
}

if (Schema::hasColumn('users', 'email')) {
    // "email"カラムを持つ"users"テーブルが存在していた
}

データベース接続とテーブルオプションDatabase Connection & Table Options

アプリケーションのデフォルトではないデータベース接続でスキーマ操作を実行する場合は、connectionメソッドを使用します。If you want to perform a schema operation on a database connection that is not your application's default connection, use the connection method:

Schema::connection('sqlite')->create('users', function (Blueprint $table) {
    $table->id();
});

さらに、他のプロパティやメソッドを使用して、テーブル作成の他の部分を定義できます。engineプロパティはMySQLを使用するときにテーブルのストレージエンジンを指定するために使用します。In addition, a few other properties and methods may be used to define other aspects of the table's creation. The engine property may be used to specify the table's storage engine when using MySQL:

Schema::create('users', function (Blueprint $table) {
    $table->engine = 'InnoDB';

    // ...
});

charsetプロパティとcollat​​ionプロパティはMySQLを使用するときに、作成されたテーブルの文字セットと照合順序を指定するために使用します。The charset and collation properties may be used to specify the character set and collation for the created table when using MySQL:

Schema::create('users', function (Blueprint $table) {
    $table->charset = 'utf8mb4';
    $table->collation = 'utf8mb4_unicode_ci';

    // ...
});

temporaryメソッドを使用して、テーブルを「一時的」にする必要があることを示すことができます。一時テーブルは、現在の接続のデータベースセッションにのみ表示され、接続が閉じられると自動的に削除されます。The temporary method may be used to indicate that the table should be "temporary". Temporary tables are only visible to the current connection's database session and are dropped automatically when the connection is closed:

Schema::create('calculations', function (Blueprint $table) {
    $table->temporary();

    // ...
});

テーブルの更新Updating Tables

Schemaファサードのtableメソッドを使用して、既存のテーブルを更新できます。createメソッドと同様に、tableメソッドは2つの引数を取ります。テーブルの名前とテーブルにカラムやインデックスを追加するために使用できるBlueprintインスタンスを受け取るクロージャです。The table method on the Schema facade may be used to update existing tables. Like the create method, the table method accepts two arguments: the name of the table and a closure that receives a Blueprint instance you may use to add columns or indexes to the table:

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

Schema::table('users', function (Blueprint $table) {
    $table->integer('votes');
});

テーブルのリネーム/削除Renaming / Dropping Tables

既存のデータベーステーブルの名前を変更するには、renameメソッドを使用します。To rename an existing database table, use the rename method:

use Illuminate\Support\Facades\Schema;

Schema::rename($from, $to);

既存のテーブルを削除するには、dropまたはdropIfExistsメソッドを使用できます。To drop an existing table, you may use the drop or dropIfExists methods:

Schema::drop('users');

Schema::dropIfExists('users');

外部キーを使用したテーブルのリネームRenaming Tables With Foreign Keys

テーブルをリネームする前に、Laravelのテーブル名ベースの命名規約で外部キーを割り当てさせるのではなく、マイグレーションファイルでテーブルの外部キー制約の名前を明示的に指定していることを確認する必要があります。そうでない場合、外部キー制約名は古いテーブル名で参照されることになるでしょう。Before renaming a table, you should verify that any foreign key constraints on the table have an explicit name in your migration files instead of letting Laravel assign a convention based name. Otherwise, the foreign key constraint name will refer to the old table name.

カラムColumns

カラムの生成Creating Columns

Schemaファサードのtableメソッドを使用して、既存のテーブルを更新できます。createメソッドと同様に、tableメソッドは2つの引数を取ります。テーブルの名前とテーブルに列を追加するために使用できるIlluminate\Database\Schema\Blueprintインスタンスを受け取るクロージャです。The table method on the Schema facade may be used to update existing tables. Like the create method, the table method accepts two arguments: the name of the table and a closure that receives an Illuminate\Database\Schema\Blueprint instance you may use to add columns to the table:

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

Schema::table('users', function (Blueprint $table) {
    $table->integer('votes');
});

利用可能なカラムタイプAvailable Column Types

スキーマビルダのBlueprintは、データベーステーブルに追加できるさまざまなタイプのカラムに対応する、多くのメソッドを提供しています。使用可能な各メソッドを以下に一覧します。The schema builder blueprint offers a variety of methods that correspond to the different types of columns you can add to your database tables. Each of the available methods are listed in the table below:

bigIncrements() bigIncrements()

bigIncrementsメソッドは、自動増分するUNSIGNED BIGINT(主キー)カラムを作成します。The bigIncrements method creates an auto-incrementing UNSIGNED BIGINT (primary key) equivalent column:

$table->bigIncrements('id');

bigInteger() bigInteger()

bigIntegerメソッドはBIGINTカラムを作成します。The bigInteger method creates a BIGINT equivalent column:

$table->bigInteger('votes');

binary() binary()

binaryメソッドはBLOBカラムを作成します。The binary method creates a BLOB equivalent column:

$table->binary('photo');

boolean() boolean()

booleanメソッドはBOOLEANカラムを作成します。The boolean method creates a BOOLEAN equivalent column:

$table->boolean('confirmed');

char() char()

charメソッドは、指定した長さのCHARカラムを作成します。The char method creates a CHAR equivalent column with of a given length:

$table->char('name', 100);

dateTimeTz() dateTimeTz()

dateTimeTzメソッドは、オプションの精度(合計桁数)でDATETIME(タイムゾーン付き)カラムを作成します。The dateTimeTz method creates a DATETIME (with timezone) equivalent column with an optional precision (total digits):

$table->dateTimeTz('created_at', $precision = 0);

dateTime() dateTime()

dateTimeメソッドは、オプションの精度(合計桁数)でDATETIMEカラムを作成します。The dateTime method creates a DATETIME equivalent column with an optional precision (total digits):

$table->dateTime('created_at', $precision = 0);

date() date()

dateメソッドはDATEカラムを作成します。The date method creates a DATE equivalent column:

$table->date('created_at');

decimal() decimal()

decimalメソッドは、指定した精度(合計桁数)とスケール(小数桁数)でDECIMALカラムを作成します。The decimal method creates a DECIMAL equivalent column with the given precision (total digits) and scale (decimal digits):

$table->decimal('amount', $precision = 8, $scale = 2);

double() double()

doubleメソッドは、指定した精度(合計桁数)とスケール(小数桁数)でDOUBLEカラムを作成します。The double method creates a DOUBLE equivalent column with the given precision (total digits) and scale (decimal digits):

$table->double('amount', 8, 2);

enum() enum()

enumメソッドは、指定した有効な値でENUMカラムを作成します。The enum method creates a ENUM equivalent column with the given valid values:

$table->enum('difficulty', ['easy', 'hard']);

float() float()

floatメソッドは、指定した精度(合計桁数)とスケール(小数桁数)でFLOATカラムを作成します。The float method creates a FLOAT equivalent column with the given precision (total digits) and scale (decimal digits):

$table->float('amount', 8, 2);

foreignId() foreignId()

foreignIdメソッドはUNSIGNED BIGINTカラムを作成します。The foreignId method creates an UNSIGNED BIGINT equivalent column:

$table->foreignId('user_id');

foreignIdFor() foreignIdFor()

foreignIdForメソッドは、指定モデルクラスへ{column}_id UNSIGNED BIGINTを追加します。The foreignIdFor method adds a {column}_id UNSIGNED BIGINT equivalent column for a given model class:

$table->foreignIdFor(User::class);

foreignUuid() foreignUuid()

foreignUuidメソッドはUUIDカラムを作成します。The foreignUuid method creates a UUID equivalent column:

$table->foreignUuid('user_id');

geometryCollection() geometryCollection()

geometryCollectionメソッドはGEOMETRYCOLLECTIONカラムを作成します。The geometryCollection method creates a GEOMETRYCOLLECTION equivalent column:

$table->geometryCollection('positions');

geometry() geometry()

geometryメソッドはGEOMETRYカラムを作成します。The geometry method creates a GEOMETRY equivalent column:

$table->geometry('positions');

id() id()

idメソッドはbigIncrementsメソッドのエイリアスです。デフォルトでは、メソッドはidカラムを作成します。ただし、カラムに別の名前を割り当てたい場合は、カラム名を渡すことができます。The id method is an alias of the bigIncrements method. By default, the method will create an id column; however, you may pass a column name if you would like to assign a different name to the column:

$table->id();

increments() increments()

incrementsメソッドは、主キーとして自動増分のUNSIGNED INTEGERカラムを作成します。The increments method creates an auto-incrementing UNSIGNED INTEGER equivalent column as a primary key:

$table->increments('id');

integer() integer()

integerメソッドは INTEGERカラムを作成します。The integer method creates an INTEGER equivalent column:

$table->integer('votes');

ipAddress() ipAddress()

ipAddressメソッドはVARCHARカラムを作成します。The ipAddress method creates a VARCHAR equivalent column:

$table->ipAddress('visitor');

json() json()

jsonメソッドはJSONカラムを作成します。The json method creates a JSON equivalent column:

$table->json('options');

jsonb() jsonb()

jsonbメソッドはJSONBカラムを作成します。The jsonb method creates a JSONB equivalent column:

$table->jsonb('options');

lineString() lineString()

lineStringメソッドはLINESTRINGカラムを作成します。The lineString method creates a LINESTRING equivalent column:

$table->lineString('positions');

longText() longText()

longTextメソッドはLONGTEXTカラムを作成します。The longText method creates a LONGTEXT equivalent column:

$table->longText('description');

macAddress() macAddress()

macAddressメソッドは、MACアドレスを保持することを目的としたカラムを作成します。PostgreSQLなどの一部のデータベースシステムには、このタイプのデータ専用のカラムタイプがあります。他のデータベースシステムでは、文字カラムに相当するカラムを使用します。The macAddress method creates a column that is intended to hold a MAC address. Some database systems, such as PostgreSQL, have a dedicated column type for this type of data. Other database systems will use a string equivalent column:

$table->macAddress('device');

mediumIncrements() mediumIncrements()

mediumIncrementsメソッドは、主キーが自動増分のUNSIGNED MEDIUMINTカラムを作成します。The mediumIncrements method creates an auto-incrementing UNSIGNED MEDIUMINT equivalent column as a primary key:

$table->mediumIncrements('id');

mediumInteger() mediumInteger()

mediumIntegerメソッドはMEDIUMINTカラムを作成します。The mediumInteger method creates a MEDIUMINT equivalent column:

$table->mediumInteger('votes');

mediumText() mediumText()

mediumTextメソッドはMEDIUMTEXTカラムを作成します。The mediumText method creates a MEDIUMTEXT equivalent column:

$table->mediumText('description');

morphs() morphs()

morphsメソッドは、{column}_id UNSIGNED BIGINTカラムと、{column}_type VARCHARカラムを追加する便利なメソッドです。The morphs method is a convenience method that adds a {column}_id UNSIGNED BIGINT equivalent column and a {column}_type VARCHAR equivalent column.

このメソッドは、ポリモーフィックEloquentリレーションに必要なカラムを定義するときに使用することを目的としています。次の例では、taggable_idカラムとtaggable_typeカラムが作成されます。This method is intended to be used when defining the columns necessary for a polymorphic Eloquent relationship[/docs/{{version}}/eloquent-relationships]. In the following example, taggable_id and taggable_type columns would be created:

$table->morphs('taggable');

multiLineString() multiLineString()

multiLineStringメソッドはMULTILINESTRINGカラムを作成します。The multiLineString method creates a MULTILINESTRING equivalent column:

$table->multiLineString('positions');

multiPoint() multiPoint()

multiPointメソッドはMULTIPOINTカラムを作成します。The multiPoint method creates a MULTIPOINT equivalent column:

$table->multiPoint('positions');

multiPolygon() multiPolygon()

multiPolygonメソッドはMULTIPOLYGONカラムを作成します。The multiPolygon method creates a MULTIPOLYGON equivalent column:

$table->multiPolygon('positions');

nullableTimestamps() nullableTimestamps()

nullableTimestampsメソッドはtimestampsメソッドのエイリアスです。The nullableTimestamps method is an alias of the timestamps[#column-method-timestamps] method:

$table->nullableTimestamps(0);

nullableMorphs() nullableMorphs()

このメソッドは、morphsメソッドに似ています。ただし、作成するカラムは"NULLABLE"になります。The method is similar to the morphs[#column-method-morphs] method; however, the columns that are created will be "nullable":

$table->nullableMorphs('taggable');

nullableUuidMorphs() nullableUuidMorphs()

このメソッドは、uuidMorphsメソッドに似ています。ただし、作成するカラムは"NULLABLE"になります。The method is similar to the uuidMorphs[#column-method-uuidMorphs] method; however, the columns that are created will be "nullable":

$table->nullableUuidMorphs('taggable');

point() point()

pointメソッドはPOINTカラムを作成します。The point method creates a POINT equivalent column:

$table->point('position');

polygon() polygon()

polygonメソッドはPOLYGONカラムを作成します。The polygon method creates a POLYGON equivalent column:

$table->polygon('position');

rememberToken() rememberToken()

rememberTokenメソッドは、現在の「ログイン持続("remember me")」認証トークンを格納することを目的としたNULL許容のVARCHAR(100)相当のカラムを作成します。The rememberToken method creates a nullable, VARCHAR(100) equivalent column that is intended to store the current "remember me" authentication token[/docs/{{version}}/authentication#remembering-users]:

$table->rememberToken();

set() set()

setメソッドは、指定した有効な値のリストを使用して、SETカラムを作成します。The set method creates a SET equivalent column with the given list of valid values:

$table->set('flavors', ['strawberry', 'vanilla']);

smallIncrements() smallIncrements()

smallIncrementsメソッドは、主キーとして自動増分のUNSIGNED SMALLINTカラムを作成します。The smallIncrements method creates an auto-incrementing UNSIGNED SMALLINT equivalent column as a primary key:

$table->smallIncrements('id');

smallInteger() smallInteger()

smallIntegerメソッドはSMALLINTカラムを作成します。The smallInteger method creates a SMALLINT equivalent column:

$table->smallInteger('votes');

softDeletesTz() softDeletesTz()

softDeletesTzメソッドは、オプションの精度(合計桁数)でNULL許容のdeleted_at TIMESTAMP(タイムゾーン付き)カラムを追加します。このカラムは、Eloquentの「ソフトデリート」機能に必要なdeleted_atタイムスタンプを格納するためのものです。The softDeletesTz method adds a nullable deleted_at TIMESTAMP (with timezone) equivalent column with an optional precision (total digits). This column is intended to store the deleted_at timestamp needed for Eloquent's "soft delete" functionality:

$table->softDeletesTz($column = 'deleted_at', $precision = 0);

softDeletes() softDeletes()

softDeletesメソッドは、オプションの精度(合計桁数)でNULL許容のdeleted_at TIMESTAMPカラムを追加します。このカラムは、Eloquentの「ソフトデリート」機能に必要なdeleted_atタイムスタンプを格納するためのものです。The softDeletes method adds a nullable deleted_at TIMESTAMP equivalent column with an optional precision (total digits). This column is intended to store the deleted_at timestamp needed for Eloquent's "soft delete" functionality:

$table->softDeletes($column = 'deleted_at', $precision = 0);

string() string()

stringメソッドは、指定された長さのVARCHARカラムを作成します。The string method creates a VARCHAR equivalent column of the given length:

$table->string('name', 100);

text() text()

textメソッドはTEXTカラムを作成します。The text method creates a TEXT equivalent column:

$table->text('description');

timeTz() timeTz()

timeTzメソッドは、オプションの精度(合計桁数)でTIME(タイムゾーン付き)カラムを作成します。The timeTz method creates a TIME (with timezone) equivalent column with an optional precision (total digits):

$table->timeTz('sunrise', $precision = 0);

time() time()

timeメソッドは、オプションの精度(合計桁数)でTIMEカラムを作成します。The time method creates a TIME equivalent column with an optional precision (total digits):

$table->time('sunrise', $precision = 0);

timestampTz() timestampTz()

timestampTzメソッドは、オプションの精度(合計桁数)でTIMESTAMP(タイムゾーン付き)カラムを作成します。The timestampTz method creates a TIMESTAMP (with timezone) equivalent column with an optional precision (total digits):

$table->timestampTz('added_at', $precision = 0);

timestamp() timestamp()

timestampメソッドは、オプションの精度(合計桁数)でTIMESTAMPカラムを作成します。The timestamp method creates a TIMESTAMP equivalent column with an optional precision (total digits):

$table->timestamp('added_at', $precision = 0);

timestampsTz() timestampsTz()

timestampsTzメソッドは、オプションの精度(合計桁数)でcreated_atおよびupdated_at TIMESTAMP(タイムゾーン付き)カラムを作成します。The timestampsTz method creates created_at and updated_at TIMESTAMP (with timezone) equivalent columns with an optional precision (total digits):

$table->timestampsTz($precision = 0);

timestamps() timestamps()

timestampsメソッドは、オプションの精度(合計桁数)でcreated_atおよびupdated_at TIMESTAMPカラムを作成します。The timestamps method creates created_at and updated_at TIMESTAMP equivalent columns with an optional precision (total digits):

$table->timestamps($precision = 0);

tinyIncrements() tinyIncrements()

tinyIncrementsメソッドは、主キーとして自動増分のUNSIGNED TINYINTカラムを作成します。The tinyIncrements method creates an auto-incrementing UNSIGNED TINYINT equivalent column as a primary key:

$table->tinyIncrements('id');

tinyInteger() tinyInteger()

tinyIntegerメソッドはTINYINTカラムを作成します。The tinyInteger method creates a TINYINT equivalent column:

$table->tinyInteger('votes');

tinyText() tinyText()

TinyTextメソッドはTINYTEXTカラムを作成します。The tinyText method creates a TINYTEXT equivalent column:

$table->tinyText('notes');

unsignedBigInteger() unsignedBigInteger()

unsignedBigIntegerメソッドはUNSIGNED BIGINTカラムを作成します。The unsignedBigInteger method creates an UNSIGNED BIGINT equivalent column:

$table->unsignedBigInteger('votes');

unsignedDecimal() unsignedDecimal()

unsignedDecimalメソッドは、オプションの精度(合計桁数)とスケール(小数桁数)を使用して、UNSIGNED DECIMALカラムを作成します。The unsignedDecimal method creates an UNSIGNED DECIMAL equivalent column with an optional precision (total digits) and scale (decimal digits):

$table->unsignedDecimal('amount', $precision = 8, $scale = 2);

unsignedInteger() unsignedInteger()

unsignedIntegerメソッドはUNSIGNED INTEGERカラムを作成します。The unsignedInteger method creates an UNSIGNED INTEGER equivalent column:

$table->unsignedInteger('votes');

unsignedMediumInteger() unsignedMediumInteger()

unsignedMediumIntegerメソッドは、UNSIGNED MEDIUMINTカラムを作成します。The unsignedMediumInteger method creates an UNSIGNED MEDIUMINT equivalent column:

$table->unsignedMediumInteger('votes');

unsignedSmallInteger() unsignedSmallInteger()

unsignedSmallIntegerメソッドはUNSIGNED SMALLINTカラムを作成します。The unsignedSmallInteger method creates an UNSIGNED SMALLINT equivalent column:

$table->unsignedSmallInteger('votes');

unsignedTinyInteger() unsignedTinyInteger()

unsignedTinyIntegerメソッドは UNSIGNED TINYINTカラムを作成します。The unsignedTinyInteger method creates an UNSIGNED TINYINT equivalent column:

$table->unsignedTinyInteger('votes');

uuidMorphs() uuidMorphs()

uuidMorphsメソッドは、{column}_id CHAR(36)カラムと、{column}_type VARCHARカラムを追加する便利なメソッドです。The uuidMorphs method is a convenience method that adds a {column}_id CHAR(36) equivalent column and a {column}_type VARCHAR equivalent column.

このメソッドは、UUID識別子を使用するポリモーフィックなEloquentリレーションに必要なカラムを定義するときに使用します。以下の例では、taggable_idカラムとtaggable_typeカラムが作成されます。This method is intended to be used when defining the columns necessary for a polymorphic Eloquent relationship[/docs/{{version}}/eloquent-relationships] that use UUID identifiers. In the following example, taggable_id and taggable_type columns would be created:

$table->uuidMorphs('taggable');

uuid() uuid()

uuidメソッドはUUIDカラムを作成します。The uuid method creates a UUID equivalent column:

$table->uuid('id');

year() year()

yearメソッドはYEARカラムを作成します。The year method creates a YEAR equivalent column:

$table->year('birth_year');

カラム修飾子Column Modifiers

上記リストのカラムタイプに加え、データベーステーブルにカラムを追加するときに使用できるカラム「修飾子」もあります。たとえば、カラムを"NULLABLE"へするために、nullableメソッドが使用できます。In addition to the column types listed above, there are several column "modifiers" you may use when adding a column to a database table. For example, to make the column "nullable", you may use the nullable method:

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

Schema::table('users', function (Blueprint $table) {
    $table->string('email')->nullable();
});

次の表は、使用可能なすべてのカラム修飾子を紹介しています。このリストにはインデックス修飾子は含まれていません。The following table contains all of the available column modifiers. This list does not include index modifiers[#creating-indexes]:

修飾子Modifier 説明Description
->after('column')->after('column') カラムを別のカラムの「後に」配置(MySQL)Place the column "after" another column (MySQL).
->autoIncrement()->autoIncrement() INTEGERカラムを自動増分(主キー)として設定Set INTEGER columns as auto-incrementing (primary key).
->charset('utf8mb4')->charset('utf8mb4') カラムの文字セットを指定(MySQL)Specify a character set for the column (MySQL).
->collation('utf8mb4_unicode_ci')->collation('utf8mb4_unicode_ci') カラムの照合順序を指定(MySQL/PostgreSQL/SQL Server)Specify a collation for the column (MySQL/PostgreSQL/SQL Server).
->comment('my comment')->comment('my comment') カラムにコメントを追加(MySQL/PostgreSQL)Add a comment to a column (MySQL/PostgreSQL).
->default($value)->default($value) カラムの「デフォルト」値を指定Specify a "default" value for the column.
->first()->first() テーブルの「最初の」カラムを配置(MySQL)Place the column "first" in the table (MySQL).
->from($integer)->from($integer) 自動増分フィールドの開始値を設定(MySQL/PostgreSQL)Set the starting value of an auto-incrementing field (MySQL / PostgreSQL).
->invisible()->invisible() SELECT *クエリに対しカラムを「不可視」にする(MySQL)Make the column "invisible" to SELECT * queries (MySQL).
->nullable($value = true)->nullable($value = true) NULL値をカラムに保存可能に設定Allow NULL values to be inserted into the column.
->storedAs($expression)->storedAs($expression) stored generatedカラムを作成(MySQL/PostgreSQL)Create a stored generated column (MySQL / PostgreSQL).
->unsigned()->unsigned() INTEGERカラムをUNSIGNEDとして設定(MySQL)Set INTEGER columns as UNSIGNED (MySQL).
->useCurrent()->useCurrent() CURRENT_TIMESTAMPをデフォルト値として使用するようにTIMESTAMPカラムを設定Set TIMESTAMP columns to use CURRENT_TIMESTAMP as default value.
->useCurrentOnUpdate()->useCurrentOnUpdate() レコードが更新されたときにCURRENT_TIMESTAMPを使用するようにTIMESTAMPカラムを設定Set TIMESTAMP columns to use CURRENT_TIMESTAMP when a record is updated.
->virtualAs($expression)->virtualAs($expression) virtual generatedカラムを作成(MySQL)Create a virtual generated column (MySQL).
->generatedAs($expression)->generatedAs($expression) 指定のシーケンスオプションで、識別カラムを生成(PostgreSQL)Create an identity column with specified sequence options (PostgreSQL).
->always()->always() IDカラムの入力に対するシーケンス値の優先順位を定義(PostgreSQL)Defines the precedence of sequence values over input for an identity column (PostgreSQL).
->isGeometry()->isGeometry() 空間カラムのタイプをgeometryに設定 - デフォルトタイプはgeography(PostgreSQL)Set spatial column type to geometry - the default type is geography (PostgreSQL).

デフォルト式Default Expressions

default修飾子は、値またはIlluminate\Database\Query\Expressionインスタンスを受け入れます。Expressionインスタンスを使用すると、Laravelが値を引用符で囲むのを防ぎ、データベース固有の関数を使用できるようになります。これがとくに役立つ状況の1つは、JSONカラムにデフォルト値を割り当てる必要がある場合です。The default modifier accepts a value or an Illuminate\Database\Query\Expression instance. Using an Expression instance will prevent Laravel from wrapping the value in quotes and allow you to use database specific functions. One situation where this is particularly useful is when you need to assign default values to JSON columns:

<?php

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

class CreateFlightsTable extends Migration
{
    /**
     * マイグレーションの実行
     *
     * @return void
     */
    public function up()
    {
        Schema::create('flights', function (Blueprint $table) {
            $table->id();
            $table->json('movies')->default(new Expression('(JSON_ARRAY())'));
            $table->timestamps();
        });
    }
}

Note: note デフォルト式のサポートは、データベースドライバー、データベースバージョン、およびフィールドタイプによって異なります。データベースのドキュメントを参照してください。{note} Support for default expressions depends on your database driver, database version, and the field type. Please refer to your database's documentation.

カラム順序Column Order

MySQLデータベースを使用するときは、スキーマ内の既存の列の後に列を追加するためにafterメソッドを使用できます。When using the MySQL database, the after method may be used to add columns after an existing column in the schema:

$table->after('password', function ($table) {
    $table->string('address_line1');
    $table->string('address_line2');
    $table->string('city');
});

カラムの変更Modifying Columns

前提条件Prerequisites

カラムを変更する前に、Composerパッケージマネージャーを使用してdoctrine/dbalパッケージをインストールする必要があります。DoctrineDBALライブラリは、カラムの現在の状態を判別し、カラムに要求された変更を加えるために必要なSQLクエリを作成するのに使用します。Before modifying a column, you must install the doctrine/dbal package using the Composer package manager. The Doctrine DBAL library is used to determine the current state of the column and to create the SQL queries needed to make the requested changes to your column:

composer require doctrine/dbal

timestampメソッドを使用して作成したカラムを変更する予定があるときは、アプリケーションのconfig/database.php設定ファイルに以下の設定を追加する必要があります。If you plan to modify columns created using the timestamp method, you must also add the following configuration to your application's config/database.php configuration file:

use Illuminate\Database\DBAL\TimestampType;

'dbal' => [
    'types' => [
        'timestamp' => TimestampType::class,
    ],
],

Note: note アプリケーションでMicrosoft SQL Serverを使用している場合は、doctrine/dbal:^3.0を確実にインストールしてください。{note} If your application is using Microsoft SQL Server, please ensure that you install doctrine/dbal:^3.0.

カラム属性の更新Updating Column Attributes

changeメソッドを使用すると、既存のカラムのタイプと属性を変更できます。たとえば、stringカラムのサイズを大きくしたい場合があります。changeメソッドの動作を確認するために、nameカラムのサイズを25から50に増やしてみましょう。これを実行するには、カラムの新しい状態を定義してから、changeメソッドを呼び出します。The change method allows you to modify the type and attributes of existing columns. For example, you may wish to increase the size of a string column. To see the change method in action, let's increase the size of the name column from 25 to 50. To accomplish this, we simply define the new state of the column and then call the change method:

Schema::table('users', function (Blueprint $table) {
    $table->string('name', 50)->change();
});

カラムをNULLABLEへ変更することもできます。We could also modify a column to be nullable:

Schema::table('users', function (Blueprint $table) {
    $table->string('name', 50)->nullable()->change();
});

Note: note 以降のカラムタイプを変更できます。bigIntegerbinarybooleandatedateTimedateTimeTzdecimalintegerjsonlongTextmediumTextsmallIntegerstringtexttimeunsignedBigIntegerunsignedIntegerunsignedSmallIntegeruuidtimestampのカラムタイプを変更するには、Doctrineタイプを登録する必要があります{note} The following column types can be modified: bigInteger, binary, boolean, date, dateTime, dateTimeTz, decimal, integer, json, longText, mediumText, smallInteger, string, text, time, unsignedBigInteger, unsignedInteger, unsignedSmallInteger, and uuid. To modify a timestamp column type a Doctrine type must be registered[#prerequisites].

カラムのリネームRenaming Columns

カラムをリネームするには、スキーマビルダBlueprintが提供するrenameColumnメソッドを使用します。カラムの名前を変更する前に、Composerパッケージマネージャーを介してdoctrine/dbalライブラリをインストールしていることを確認してください。To rename a column, you may use the renameColumn method provided by the schema builder blueprint. Before renaming a column, ensure that you have installed the doctrine/dbal library via the Composer package manager:

Schema::table('users', function (Blueprint $table) {
    $table->renameColumn('from', 'to');
});

Note: note enumカラムの名前変更は現在サポートしていません。{note} Renaming an enum column is not currently supported.

カラムの削除Dropping Columns

カラムを削除するには、スキーマビルダのBlueprintでdropColumnメソッドを使用します。アプリケーションがSQLiteデータベースを利用している場合、dropColumnメソッドを使用する前に、Composerパッケージマネージャーを介してdoctrine/dbalパッケージをインストールする必要があります。To drop a column, you may use the dropColumn method on the schema builder blueprint. If your application is utilizing an SQLite database, you must install the doctrine/dbal package via the Composer package manager before the dropColumn method may be used:

Schema::table('users', function (Blueprint $table) {
    $table->dropColumn('votes');
});

カラム名の配列をdropColumnメソッドに渡すことにより、テーブルから複数のカラムを削除できます。You may drop multiple columns from a table by passing an array of column names to the dropColumn method:

Schema::table('users', function (Blueprint $table) {
    $table->dropColumn(['votes', 'avatar', 'location']);
});

Note: note SQLiteデータベースの使用時に、1回のマイグレーションで複数のカラムを削除または変更することはサポートしていません。{note} Dropping or modifying multiple columns within a single migration while using an SQLite database is not supported.

使用可能なコマンドエイリアスAvailable Command Aliases

Laravelは、一般的なタイプのカラムの削除の便利な方法を提供しています。各メソッドは以下の表で説明します。Laravel provides several convenient methods related to dropping common types of columns. Each of these methods is described in the table below:

コマンドCommand 説明Description
$table->dropMorphs('morphable');$table->dropMorphs('morphable'); morphable_idカラムとmorphable_typeカラムを削除Drop the morphable_id and morphable_type columns.
$table->dropRememberToken();$table->dropRememberToken(); remember_tokenカラムを削除Drop the remember_token column.
$table->dropSoftDeletes();$table->dropSoftDeletes(); deleted_atカラムを削除Drop the deleted_at column.
$table->dropSoftDeletesTz();$table->dropSoftDeletesTz(); dropSoftDeletes()メソッドのエイリアスAlias of dropSoftDeletes() method.
$table->dropTimestamps();$table->dropTimestamps(); created_atカラムとupdated_atカラムを削除Drop the created_at and updated_at columns.
$table->dropTimestampsTz();$table->dropTimestampsTz(); dropTimestamps()メソッドのエイリアスAlias of dropTimestamps() method.

インデックスIndexes

インデックスの生成Creating Indexes

Laravelスキーマビルダは多くのタイプのインデックスをサポートしています。次の例では、新しいemailカラムを作成し、その値が一意であることを指定しています。インデックスを作成するには、uniqueメソッドをカラム定義にチェーンします。The Laravel schema builder supports several types of indexes. The following example creates a new email column and specifies that its values should be unique. To create the index, we can chain the unique method onto the column definition:

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

Schema::table('users', function (Blueprint $table) {
    $table->string('email')->unique();
});

または、カラムを定義した後にインデックスを作成することもできます。これを行うには、スキーマビルダBlueprintでuniqueメソッドを呼び出す必要があります。このメソッドは、一意のインデックスを受け取る必要があるカラムの名前を引数に取ります。Alternatively, you may create the index after defining the column. To do so, you should call the unique method on the schema builder blueprint. This method accepts the name of the column that should receive a unique index:

$table->unique('email');

カラムの配列をindexメソッドに渡して、複合インデックスを作成することもできます。You may even pass an array of columns to an index method to create a compound (or composite) index:

$table->index(['account_id', 'created_at']);

インデックスを作成するとき、Laravelはテーブル、カラム名、およびインデックスタイプに基づいてインデックス名を自動的に生成しますが、メソッドに2番目の引数を渡して、インデックス名を自分で指定することもできます。When creating an index, Laravel will automatically generate an index name based on the table, column names, and the index type, but you may pass a second argument to the method to specify the index name yourself:

$table->unique('email', 'unique_email');

利用可能なインデックスタイプAvailable Index Types

LaravelのスキーマビルダBlueprintクラスは、Laravelでサポートしている各タイプのインデックスを作成するメソッドを提供しています。各indexメソッドは、オプションの2番目の引数を取り、インデックスの名前を指定します。省略した場合、名前は、インデックスに使用されるテーブルとカラムの名前、およびインデックスタイプから派生します。使用可能な各インデックスメソッドは、以下の表で説明します。Laravel's schema builder blueprint class provides methods for creating each type of index supported by Laravel. Each index method accepts an optional second argument to specify the name of the index. If omitted, the name will be derived from the names of the table and column(s) used for the index, as well as the index type. Each of the available index methods is described in the table below:

コマンドCommand 説明Description
$table->primary('id');$table->primary('id'); 主キーを追加Adds a primary key.
$table->primary(['id', 'parent_id']);$table->primary(['id', 'parent_id']); 複合キーを追加Adds composite keys.
$table->unique('email');$table->unique('email'); 一意のインデックスを追加Adds a unique index.
$table->index('state');$table->index('state'); インデックスを追加Adds an index.
$table->fulltext('body');$table->fulltext('body'); フルテキストのインデックスを追加(MySQL/PostgreSQL)Adds a fulltext index (MySQL/PostgreSQL).
$table->fulltext('body')->language('english');$table->fulltext('body')->language('english'); 指定言語で、フルテキストのインデックスを追加(PostgreSQL)Adds a fulltext index of the specified language (PostgreSQL).
$table->spatialIndex('location');$table->spatialIndex('location'); 空間インデックスを追加(SQLiteを除く)Adds a spatial index (except SQLite).

インデックスの長さとMySQL/MariaDBIndex Lengths & MySQL / MariaDB

デフォルトでは、Laravelはutf8mb4文字セットを使用します。5.7.7リリースより古いバージョンのMySQLまたは10.2.2リリースより古いMariaDBを実行している場合、MySQLがそれらのインデックスを作成するために、マイグレーションによって生成されるデフォルトの文字カラム長を手動で設定する必要が起きます。App\Providers\AppServiceProviderクラスのbootメソッド内でSchema::defaultStringLengthメソッドを呼び出し、デフォルトの文字カラムの長さを設定できます。By default, Laravel uses the utf8mb4 character set. If you are running a version of MySQL older than the 5.7.7 release or MariaDB older than the 10.2.2 release, you may need to manually configure the default string length generated by migrations in order for MySQL to create indexes for them. You may configure the default string length by calling the Schema::defaultStringLength method within the boot method of your App\Providers\AppServiceProvider class:

use Illuminate\Support\Facades\Schema;

/**
 * 全アプリケーションサービスの初期設定
 *
 * @return void
 */
public function boot()
{
    Schema::defaultStringLength(191);
}

または、データベースのinnodb_large_prefixオプションを有効にすることもできます。このオプションを適切に有効にする方法については、データベースのドキュメントを参照してください。Alternatively, you may enable the innodb_large_prefix option for your database. Refer to your database's documentation for instructions on how to properly enable this option.

インデックスのリネームRenaming Indexes

インデックスの名前を変更するには、スキーマビルダBlueprintが提供するrenameIndexメソッドを使用します。このメソッドは、現在のインデックス名を最初の引数として取り、目的の名前を2番目の引数として取ります。To rename an index, you may use the renameIndex method provided by the schema builder blueprint. This method accepts the current index name as its first argument and the desired name as its second argument:

$table->renameIndex('from', 'to')

インデックスの削除Dropping Indexes

インデックスを削除するには、インデックスの名前を指定する必要があります。デフォルトでは、Laravelはテーブル名、インデックス付きカラムの名前、およびインデックスタイプに基づいてインデックス名を自動的に割り当てます。ここではいくつかの例を示します。To drop an index, you must specify the index's name. By default, Laravel automatically assigns an index name based on the table name, the name of the indexed column, and the index type. Here are some examples:

コマンドCommand 説明Description
$table->dropPrimary('users_id_primary');$table->dropPrimary('users_id_primary'); "users"テーブルから主キーを削除Drop a primary key from the "users" table.
$table->dropUnique('users_email_unique');$table->dropUnique('users_email_unique'); "users"テーブルから一意のインデックスを削除Drop a unique index from the "users" table.
$table->dropIndex('geo_state_index');$table->dropIndex('geo_state_index'); "geo"テーブルから基本インデックスを削除Drop a basic index from the "geo" table.
$table->dropSpatialIndex('geo_location_spatialindex');$table->dropSpatialIndex('geo_location_spatialindex'); "geo"テーブルから空間インデックスを削除(SQLiteを除く)Drop a spatial index from the "geo" table (except SQLite).

インデックスを削除するメソッドにカラムの配列を渡すと、テーブル名、カラム、およびインデックスタイプに基づいてインデックス名が生成されます。If you pass an array of columns into a method that drops indexes, the conventional index name will be generated based on the table name, columns, and index type:

Schema::table('geo', function (Blueprint $table) {
    $table->dropIndex(['state']); // Drops index 'geo_state_index'
});

外部キー制約Foreign Key Constraints

Laravelは、データベースレベルで参照整合性を強制するために使用される外部キー制約の作成もサポートしています。たとえば、usersテーブルのidカラムを参照するpostsテーブルのuser_idカラムを定義しましょう。Laravel also provides support for creating foreign key constraints, which are used to force referential integrity at the database level. For example, let's define a user_id column on the posts table that references the id column on a users table:

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

Schema::table('posts', function (Blueprint $table) {
    $table->unsignedBigInteger('user_id');

    $table->foreign('user_id')->references('id')->on('users');
});

この構文はかなり冗長であるため、Laravelは、より良い開発者エクスペリエンスを提供するために規約を使用した追加の簡潔なメソッドを提供します。foreignIdメソッドを使用すると、上記の例は次のように書き直すことができます。Since this syntax is rather verbose, Laravel provides additional, terser methods that use conventions to provide a better developer experience. When using the foreignId method to create your column, the example above can be rewritten like so:

Schema::table('posts', function (Blueprint $table) {
    $table->foreignId('user_id')->constrained();
});

foreignIdメソッドはUNSIGNED BIGINTカラムを作成し、constrainedメソッドは規約を使用して参照されるテーブルとカラムの名前を決定します。テーブル名がLaravelの規則と一致しない場合は、引数としてconstrainedメソッドに渡すことでテーブル名を指定できます。The foreignId method creates an UNSIGNED BIGINT equivalent column, while the constrained method will use conventions to determine the table and column name being referenced. If your table name does not match Laravel's conventions, you may specify the table name by passing it as an argument to the constrained method:

Schema::table('posts', function (Blueprint $table) {
    $table->foreignId('user_id')->constrained('users');
});

必要なアクションに"on delete"や"on update"の制約プロパティを指定することもできます。You may also specify the desired action for the "on delete" and "on update" properties of the constraint:

$table->foreignId('user_id')
      ->constrained()
      ->onUpdate('cascade')
      ->onDelete('cascade');

これらのアクションには、表現力のある別構文も用意しています。An alternative, expressive syntax is also provided for these actions:

メソッドMethod 説明Description
$table->cascadeOnUpdate();$table->cascadeOnUpdate(); 更新をカスケードします。Updates should cascade.
$table->restrictOnUpdate();$table->restrictOnUpdate(); 更新を制限します。Updates should be restricted.
$table->cascadeOnDelete();$table->cascadeOnDelete(); 削除をカスケードします。Deletes should cascade.
$table->restrictOnDelete();$table->restrictOnDelete(); 削除を制限します。Deletes should be restricted.
$table->nullOnDelete();$table->nullOnDelete(); 削除時に外部キーへNULLをセットします。Deletes should set the foreign key value to null.

追加のカラム修飾子は、constrainedメソッドの前に呼び出す必要があります。Any additional column modifiers[#column-modifiers] must be called before the constrained method:

$table->foreignId('user_id')
      ->nullable()
      ->constrained();

外部キーの削除Dropping Foreign Keys

外部キーを削除するには、dropForeignメソッドを使用して、削除する外部キー制約の名前を引数として渡してください。外部キー制約は、インデックスと同じ命名規約を使用しています。つまり、外部キー制約名は、制約内のテーブルとカラムの名前に基づいており、その後に「_foreign」サフィックスが続きます。To drop a foreign key, you may use the dropForeign method, passing the name of the foreign key constraint to be deleted as an argument. Foreign key constraints use the same naming convention as indexes. In other words, the foreign key constraint name is based on the name of the table and the columns in the constraint, followed by a "_foreign" suffix:

$table->dropForeign('posts_user_id_foreign');

または、外部キーを保持するカラム名を含む配列をdropForeignメソッドに渡すこともできます。配列は、Laravelの制約命名規約を使用して外部キー制約名に変換されます。Alternatively, you may pass an array containing the column name that holds the foreign key to the dropForeign method. The array will be converted to a foreign key constraint name using Laravel's constraint naming conventions:

$table->dropForeign(['user_id']);

外部キー制約の切り替えToggling Foreign Key Constraints

次の方法を使用して、マイグレーション内の外部キー制約を有効または無効にできます。You may enable or disable foreign key constraints within your migrations by using the following methods:

Schema::enableForeignKeyConstraints();

Schema::disableForeignKeyConstraints();

Note: note SQLiteは、デフォルトで外部キー制約を無効にします。SQLiteを使用する場合は、マイグレーションでデータベースを作成する前に、データベース設定の外部キーサポートを有効にするを確実に行ってください。さらに、SQLiteはテーブルの作成時にのみ外部キーをサポートし、テーブルを変更する場合はサポートしません{note} SQLite disables foreign key constraints by default. When using SQLite, make sure to enable foreign key support[/docs/{{version}}/database#configuration] in your database configuration before attempting to create them in your migrations. In addition, SQLite only supports foreign keys upon creation of the table and not when tables are altered[https://www.sqlite.org/omitted.html].

イベントEvents

便宜上、各マイグレート操作はイベントを発行します。以下のイベントはすべて、Illuminate\Database\Events\MigrationEvent基本クラスを継承しています。For convenience, each migration operation will dispatch an event[/docs/{{version}}/events]. All of the following events extend the base Illuminate\Database\Events\MigrationEvent class:

ClassClass DescriptionDescription
Illuminate\Database\Events\MigrationsStartedIlluminate\Database\Events\MigrationsStarted マイグレーションのバッチが実行されようとしています。A batch of migrations is about to be executed.
Illuminate\Database\Events\MigrationsEndedIlluminate\Database\Events\MigrationsEnded マイグレーションのバッチが実行終了しました。A batch of migrations has finished executing.
Illuminate\Database\Events\MigrationStartedIlluminate\Database\Events\MigrationStarted 単一マイグレーションが実行されようとしています。A single migration is about to be executed.
Illuminate\Database\Events\MigrationEndedIlluminate\Database\Events\MigrationEnded 単一マイグレーションが実行完了しました。A single migration has finished executing.

章選択

設定

明暗テーマ
light_mode
dark_mode
brightness_auto システム設定に合わせる
テーマ選択
photo_size_select_actual デフォルト
photo_size_select_actual モノクローム(白黒)
photo_size_select_actual Solarized風
photo_size_select_actual GitHub風(青ベース)
photo_size_select_actual Viva(黄緑ベース)
photo_size_select_actual Happy(紫ベース)
photo_size_select_actual Mint(緑ベース)
コードハイライトテーマ選択

明暗テーマごとに、コードハイライトのテーマを指定できます。

テーマ配色確認
スクリーン表示幅
640px
80%
90%
100%

768px以上の幅があるときのドキュメント部分表示幅です。

インデント
無し
1rem
2rem
3rem
原文確認
原文を全行表示
原文を一行ずつ表示
使用しない

※ 段落末のEボタンへカーソルオンで原文をPopupします。

Diff表示形式
色分けのみで区別
行頭の±で区別
削除線と追記で区別

※ [tl!…]形式の挿入削除行の表示形式です。

Pagination和文
ペジネーション
ペギネーション
ページネーション
ページ付け
Scaffold和文
スカフォールド
スキャフォールド
型枠生成
本文フォント

総称名以外はCSSと同様に、"〜"でエスケープしてください。

コードフォント

総称名以外はCSSと同様に、"〜"でエスケープしてください。

保存内容リセット

localStrageに保存してある設定項目をすべて削除し、デフォルト状態へ戻します。

ヘッダー項目移動

キーボード操作