Readouble

Laravel 5.7 データベース:マイグレーション

イントロダクションIntroduction

マイグレーションとはデータベースのバージョンコントロールのような機能です。アプリケーションデータベースのスキーマの更新をチームで簡単に共有できるようにしてくれます。マイグレーションは基本的にLaravelのスキーマビルダとペアで使い、アプリケーションのデータベーススキーマの作成を楽にしてくれます。もしあなたが今まで、チームメイトに彼らのローカルデータベーススキーマに手作業でカラムを追加するよう依頼したことがあるなら、データベースマイグレーションは、そうした問題を解決してくれます。Migrations are like version control for your database, allowing your team to easily modify and share the application's database schema. Migrations are typically paired with Laravel's schema builder to easily build your application's database schema. If you have ever had to tell a teammate to manually add a column to their local database schema, you've faced the problem that database migrations solve.

LaravelのSchemaファサードは、テーブルの作成や操作をサポートしてるデータベースシステム全部に対しサポートします。The Laravel Schema facade[/docs/{{version}}/facades] provides database agnostic support for creating and manipulating tables across all of Laravel's supported database systems.

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

make:migration Artisanコマンドを使いマイグレーションを生成できます。To create a migration, use the make:migration Artisan command[/docs/{{version}}/artisan]:

php artisan make:migration create_users_table

マイグレーションはdatabase/migrationsフォルダに設置されます。マイグレーションの実行順をフレームワークに知らせるため、名前にタイムスタンプが含まれています。The new migration will be placed in your database/migrations directory. Each migration file name contains a timestamp which allows Laravel to determine the order of the migrations.

--table--createオプションも、テーブル名とマイグレーションで新しいテーブルを生成するかを指定するために使用できます。これらのオプションは生成するマイグレーションスタブの中へ指定したテーブルを予め埋め込みます。The --table and --create options may also be used to indicate the name of the table and whether the migration will be creating a new table. These options pre-fill the generated migration stub file with the specified table:

php artisan make:migration create_users_table --create=users

php artisan make:migration add_votes_to_users_table --table=users

マイグレーションの生成出力先のパスを指定したい場合は、make:migrateコマンドの実行時に--pathオプションを付けてください。パスはアプリケーションのベースパスからの相対位置です。If you would like to specify a custom output 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.

マイグレーション構造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, this migration example creates a flights table:

<?php

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

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

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

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

アプリケーションで用意したマイグレーションを全部実行するには、migrate Artisanコマンドを使用します。To run all of your outstanding migrations, execute the migrate Artisan command:

php artisan migrate

Note: note Homestead仮想マシンを使用している場合、このコマンドは仮想マシン内で実行してください。{note} If you are using the Homestead virtual machine[/docs/{{version}}/homestead], you should run this command from within your virtual machine.

実働環境でのマイグレーション強制Forcing Migrations To Run In Production

いくつかのマイグレーション操作は破壊的です。つまりデーターを失う可能性があります。実働環境(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コマンドを使います。このロールバックは、最後に「一度に」実行したマイグレーションをまとめて元に戻します。To rollback the latest migration operation, you may use the rollback 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 rollback a limited number of migrations by providing the step option to the rollback command. For example, the following command will rollback 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

rollbackとmigrateの1コマンド実行Rollback & Migrate In 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 rollback & re-migrate a limited number of migrations by providing the step option to the refresh command. For example, the following command will rollback & 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

テーブルTables

テーブル作成Creating Tables

新しいデータベーステーブルを作成するには、Schemaファサードのcreateメソッドを使用します。createメソッドは引数を2つ取ります。最初はテーブルの名前で、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:

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

テーブル作成時には、テーブルのカラムを定義するためにスキーマビルダのカラムメソッドをどれでも利用できます。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

hasTablehasColumnメソッドを使えば、テーブルやカラムの存在を簡単にチェックできます。You may easily check for the existence of a table or column using the hasTable and hasColumn methods:

if (Schema::hasTable('users')) {
    //
}

if (Schema::hasColumn('users', 'email')) {
    //
}

データベース接続とテーブル操作Database Connection & Table Options

デフォルト接続以外のデータベース接続でスキーマ操作を行いたい場合は、connectionメソッドを使ってください。If you want to perform a schema operation on a database connection that is not your default connection, use the connection method:

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

テーブルのオプションを定義するため、以下のコマンドがスキーマビルダで使用できます。You may use the following commands on the schema builder to define the table's options:

コマンドCommand 説明Description
$table->engine = 'InnoDB';$table->engine = 'InnoDB'; テーブルストレージエンジンの指定(MySQL)Specify the table storage engine (MySQL).
$table->charset = 'utf8';$table->charset = 'utf8'; テーブルのデフォルトキャラクターセットの指定(MySQL)Specify a default character set for the table (MySQL).
$table->collation = 'utf8_unicode_ci';$table->collation = 'utf8_unicode_ci'; テーブルのデフォルトコロケーションの指定(MySQL)Specify a default collation for the table (MySQL).
$table->temporary();$table->temporary(); 一時テーブルの作成(SQL Server以外)Create a temporary table (except SQL Server).

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

既存のデータベーステーブルの名前を変えたい場合は、renameメソッドを使います。To rename an existing database table, use the rename method:

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

存在するテーブルを削除する場合は、dropdropIfExistsメソッドを使います。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つの引数を取ります。テーブルの名前と、テーブルにカラムを追加するために使用する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 to the table:

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

使用できるカラムタイプAvailable Column Types

スキーマビルダは、テーブルを構築する時に使用する様々なカラムタイプを持っています。The schema builder contains a variety of column types that you may specify when building your tables:

コマンドCommand 説明Description
$table->bigIncrements('id');$table->bigIncrements('id'); 符号なしBIGINTを使用した自動増分ID(主キー)Auto-incrementing UNSIGNED BIGINT (primary key) equivalent column.
$table->bigInteger('votes');$table->bigInteger('votes'); BIGINTカラムBIGINT equivalent column.
$table->binary('data');$table->binary('data'); BLOBカラムBLOB equivalent column.
$table->boolean('confirmed');$table->boolean('confirmed'); BOOLEANカラムBOOLEAN equivalent column.
$table->char('name', 100);$table->char('name', 100); オプションの文字長を指定するCHARカラムCHAR equivalent column with an optional length.
$table->date('created_at');$table->date('created_at'); DATEカラムDATE equivalent column.
$table->dateTime('created_at');$table->dateTime('created_at'); DATETIMEカラムDATETIME equivalent column.
$table->dateTimeTz('created_at');$table->dateTimeTz('created_at'); タイムゾーン付きDATETIMEカラムDATETIME (with timezone) equivalent column.
$table->decimal('amount', 8, 2);$table->decimal('amount', 8, 2); 有効(全体桁数)/小数点以下桁数指定のDECIMALカラムDECIMAL equivalent column with a precision (total digits) and scale (decimal digits).
$table->double('amount', 8, 2);$table->double('amount', 8, 2); 有効(全体桁数)/小数点以下桁数指定のDOUBLEカラムDOUBLE equivalent column with a precision (total digits) and scale (decimal digits).
$table->enum('level', ['easy', 'hard']);$table->enum('level', ['easy', 'hard']); ENUMカラムENUM equivalent column.
$table->float('amount', 8, 2);$table->float('amount', 8, 2); 有効(全体桁数)/小数点以下桁数指定のFLOATカラムFLOAT equivalent column with a precision (total digits) and scale (decimal digits).
$table->geometry('positions');$table->geometry('positions'); GEOMETRYカラムGEOMETRY equivalent column.
$table->geometryCollection('positions');$table->geometryCollection('positions'); GEOMETRYCOLLECTIONカラムGEOMETRYCOLLECTION equivalent column.
$table->increments('id');$table->increments('id'); 符号なしINTを使用した自動増分ID(主キー)Auto-incrementing UNSIGNED INTEGER (primary key) equivalent column.
$table->integer('votes');$table->integer('votes'); INTEGERカラムINTEGER equivalent column.
$table->ipAddress('visitor');$table->ipAddress('visitor'); IPアドレスカラムIP address equivalent column.
$table->json('options');$table->json('options'); JSONフィールドJSON equivalent column.
$table->jsonb('options');$table->jsonb('options'); JSONBフィールドJSONB equivalent column.
$table->lineString('positions');$table->lineString('positions'); LINESTRINGカラムLINESTRING equivalent column.
$table->longText('description');$table->longText('description'); LONGTEXTカラムLONGTEXT equivalent column.
$table->macAddress('device');$table->macAddress('device'); MACアドレスカラムMAC address equivalent column.
$table->mediumIncrements('id');$table->mediumIncrements('id'); 符号なしMEDIUMINTを使用した自動増分ID(主キー)Auto-incrementing UNSIGNED MEDIUMINT (primary key) equivalent column.
$table->mediumInteger('votes');$table->mediumInteger('votes'); MEDIUMINTカラムMEDIUMINT equivalent column.
$table->mediumText('description');$table->mediumText('description'); MEDIUMTEXTカラムMEDIUMTEXT equivalent column.
$table->morphs('taggable');$table->morphs('taggable'); 符号なしBIGINTのtaggable_idと文字列のtaggable_typeを追加Adds taggable_id UNSIGNED BIGINT and taggable_type VARCHAR equivalent columns.
$table->multiLineString('positions');$table->multiLineString('positions'); MULTILINESTRINGカラムMULTILINESTRING equivalent column.
$table->multiPoint('positions');$table->multiPoint('positions'); MULTIPOINTカラムMULTIPOINT equivalent column.
$table->multiPolygon('positions');$table->multiPolygon('positions'); MULTIPOLYGONカラムMULTIPOLYGON equivalent column.
$table->nullableMorphs('taggable');$table->nullableMorphs('taggable'); NULL値可能なmorphs()カラムAdds nullable versions of morphs() columns.
$table->nullableTimestamps();$table->nullableTimestamps(); timestamps()メソッドの別名Alias of timestamps() method.
$table->point('position');$table->point('position'); POINTカラムPOINT equivalent column.
$table->polygon('positions');$table->polygon('positions'); POLYGONカラムPOLYGON equivalent column.
$table->rememberToken();$table->rememberToken(); VARCHAR(100)でNULL値可能なremember_tokenを追加Adds a nullable remember_token VARCHAR(100) equivalent column.
$table->smallIncrements('id');$table->smallIncrements('id'); 符号なしSMALLINTを使用した自動増分ID(主キー)Auto-incrementing UNSIGNED SMALLINT (primary key) equivalent column.
$table->smallInteger('votes');$table->smallInteger('votes'); SMALLINTカラムSMALLINT equivalent column.
$table->softDeletes();$table->softDeletes(); ソフトデリートのためにNULL値可能なdeleted_at TIMESTAMPカラム追加Adds a nullable deleted_at TIMESTAMP equivalent column for soft deletes.
$table->softDeletesTz();$table->softDeletesTz(); ソフトデリートのためにNULL値可能なdeleted_atタイムゾーン付きTIMESTAMPカラム追加Adds a nullable deleted_at TIMESTAMP (with timezone) equivalent column for soft deletes.
$table->string('name', 100);$table->string('name', 100); オプションの文字長を指定したVARCHARカラムVARCHAR equivalent column with a optional length.
$table->text('description');$table->text('description'); TEXTカラムTEXT equivalent column.
$table->time('sunrise');$table->time('sunrise'); TIMEカラムTIME equivalent column.
$table->timeTz('sunrise');$table->timeTz('sunrise'); タイムゾーン付きTIMEカラムTIME (with timezone) equivalent column.
$table->timestamp('added_on');$table->timestamp('added_on'); TIMESTAMPカラムTIMESTAMP equivalent column.
$table->timestampTz('added_on');$table->timestampTz('added_on'); タイムゾーン付きTIMESTAMPカラムTIMESTAMP (with timezone) equivalent column.
$table->timestamps();$table->timestamps(); NULL値可能なcreated_atupdated_atカラム追加Adds nullable created_at and updated_at TIMESTAMP equivalent columns.
$table->timestampsTz();$table->timestampsTz(); タイムゾーン付きのNULL値可能なcreated_atupdated_atカラム追加Adds nullable created_at and updated_at TIMESTAMP (with timezone) equivalent columns.
$table->tinyIncrements('id');$table->tinyIncrements('id'); 符号なしTINYINTを使用した自動増分ID(主キー)Auto-incrementing UNSIGNED TINYINT (primary key) equivalent column.
$table->tinyInteger('votes');$table->tinyInteger('votes'); TINYINTカラムTINYINT equivalent column.
$table->unsignedBigInteger('votes');$table->unsignedBigInteger('votes'); 符号なしBIGINTカラムUNSIGNED BIGINT equivalent column.
$table->unsignedDecimal('amount', 8, 2);$table->unsignedDecimal('amount', 8, 2); 有効(全体桁数)/小数点以下桁数指定の符号なしDECIMALカラムUNSIGNED DECIMAL equivalent column with a precision (total digits) and scale (decimal digits).
$table->unsignedInteger('votes');$table->unsignedInteger('votes'); 符号なしINTカラムUNSIGNED INTEGER equivalent column.
$table->unsignedMediumInteger('votes');$table->unsignedMediumInteger('votes'); 符号なしMEDIUMINTカラムUNSIGNED MEDIUMINT equivalent column.
$table->unsignedSmallInteger('votes');$table->unsignedSmallInteger('votes'); 符号なしSMALLINTカラムUNSIGNED SMALLINT equivalent column.
$table->unsignedTinyInteger('votes');$table->unsignedTinyInteger('votes'); 符号なしTINYINTカラムUNSIGNED TINYINT equivalent column.
$table->uuid('id');$table->uuid('id'); UUIDカラムUUID equivalent column.
$table->year('birth_year');$table->year('birth_year'); YEARカラムYEAR equivalent column.

カラム修飾子Column Modifiers

上記のカラムタイプに付け加え、カラムを追加するときに使用できる様々な修飾子もあります。たとえばカラムを「NULL値設定可能(nullable)」にしたい場合は、nullableメソッドを使います。In addition to the column types listed above, there are several column "modifiers" you may use while adding a column to a database table. For example, to make the column "nullable", you may use the nullable method:

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

下表が使用可能なカラム修飾子の一覧です。インデックス修飾子は含まれていません。Below is a list of all the available column modifiers. This list does not include the index modifiers[#creating-indexes]:

修飾子Modifier 説明Description
->after('column')->after('column') 指定カラムの次に他のカラムを設置(MySQLのみ)Place the column "after" another column (MySQL)
->autoIncrement()->autoIncrement() 整数カラムを自動増分ID(主キー)へ設定Set INTEGER columns as auto-increment (primary key)
->charset('utf8')->charset('utf8') カラムへキャラクタセットを指定(MySQLのみ)Specify a character set for the column (MySQL)
->collation('utf8_unicode_ci')->collation('utf8_unicode_ci') カラムへコロケーションを指定(MySQL/SQL Serverのみ)Specify a collation for the column (MySQL/SQL Server)
->comment('my comment')->comment('my comment') カラムにコメント追加(MySQL/PostgreSQLのみ)Add a comment to a column (MySQL/PostgreSQL)
->default($value)->default($value) カラムのデフォルト(default)値設定Specify a "default" value for the column
->first()->first() カラムをテーブルの最初(first)に設置する(MySQLのみ)Place the column "first" in the table (MySQL)
->nullable($value = true)->nullable($value = true) (デフォルトで)NULL値をカラムに挿入するAllows (by default) NULL values to be inserted into the column
->storedAs($expression)->storedAs($expression) stored generatedカラムを生成(MySQLのみ)Create a stored generated column (MySQL)
->unsigned()->unsigned() 整数カラムを符号なしに設定(MySQLのみ)Set INTEGER columns as UNSIGNED (MySQL)
->useCurrent()->useCurrent() TIMESTAMPカラムのデフォルト値をCURRENT_TIMESTAMPに指定Set TIMESTAMP columns to use CURRENT_TIMESTAMP as default value
->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() 識別カラムの入力を上書きするシーケンス値を定義(PostgreSQLのみ)Defines the precedence of sequence values over input for an identity column (PostgreSQL)

カラム変更Modifying Columns

動作要件Prerequisites

カラムを変更する前に、composer.jsonファイルでdoctrine/dbalを確実に追加してください。Doctrine DBALライブラリーは現在のカラムの状態を決め、指定されたカラムに対する修正を行うSQLクエリを生成するために、使用しています。Before modifying a column, be sure to add the doctrine/dbal dependency to your composer.json file. The Doctrine DBAL library is used to determine the current state of the column and create the SQL queries needed to make the specified adjustments to the column:

composer require doctrine/dbal

カラム属性の変更Updating Column Attributes

changeメソッドは存在するカラムを新しいタイプへ変更するか、カラムの属性を変えます。たとえば文字列の長さを増やしたい場合です。changeの実例を見てもらうため、nameカラムのサイズを25から50へ増やしてみます。The change method allows you to modify some existing column types to a new type or modify the column's attributes. 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:

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

さらにカラムをNULL値設定可能にしてみましょう。We could also modify a column to be nullable:

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

Note: note 以降のカラムタイプのみ変更可能です:bigInteger、binary、boolean、date、dateTime、dateTimeTz、decimal、integer、json、longText、mediumText、smallInteger、string、text、time、unsignedBigInteger、unsignedInteger and unsignedSmallInteger{note} Only the following column types can be "changed": bigInteger, binary, boolean, date, dateTime, dateTimeTz, decimal, integer, json, longText, mediumText, smallInteger, string, text, time, unsignedBigInteger, unsignedInteger and unsignedSmallInteger.

カラム名変更Renaming Columns

カラム名を変更するには、renameColumnメソッドをスキーマビルダで使用してください。カラム名を変更する前に、composer.jsonファイルでdoctrine/dbalを依存パッケージとして追加してください。To rename a column, you may use the renameColumn method on the Schema builder. Before renaming a column, be sure to add the doctrine/dbal dependency to your composer.json file:

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

Note: note カラムタイプがenumのテーブル中のカラム名変更は、現在サポートしていません。{note} Renaming any column in a table that also has a column of type enum is not currently supported.

カラム削除Dropping Columns

カラムをドロップするには、スキーマビルダのdropColumnメソッドを使用します。SQLiteデータベースからカラムをドロップする場合は、事前にcomposer.jsonファイルへdoctrine/dbal依存パッケージを追加してください。その後にライブラリーをインストールするため、ターミナルでcomposer updateを実行してください。To drop a column, use the dropColumn method on the Schema builder. Before dropping columns from a SQLite database, you will need to add the doctrine/dbal dependency to your composer.json file and run the composer update command in your terminal to install the library:

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使用時に、一つのマイグレーションによる複数カラム削除/変更はサポートされていません。{note} Dropping or modifying multiple columns within a single migration while using a SQLite database is not supported.

利用可能な別名コマンドAvailable Command Aliases

コマンドCommand 説明Description
$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_atupdated_atカラムのドロップDrop the created_at and updated_at columns.
$table->dropTimestampsTz();$table->dropTimestampsTz(); dropTimestamps()メソッドの別名Alias of dropTimestamps() method.

インデックスIndexes

インデックス作成Creating Indexes

スキーマビルダは様々なインデックスタイプをサポートしています。まず指定したカラムの値を一意にする例を見てください。インデックスを作成するには、カラム定義にuniqueメソッドをチェーンで付け加えます。The schema builder supports several types of indexes. First, let's look at an example that specifies a column's values should be unique. To create the index, we can chain the unique method onto the column definition:

$table->string('email')->unique();

もしくはカラム定義の後でインデックスを作成することも可能です。例を見てください。Alternatively, you may create the index after defining the column. For example:

$table->unique('email');

インデックスメソッドにカラムの配列を渡し、複合インデックスを作成することもできます。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引数で、名前を指定することもできます。Laravel will automatically generate a reasonable index name, but you may pass a second argument to the method to specify the name yourself:

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

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

各インデックスメソッドは、オプションとして第2引数に、インデックス名を指定できます。省略した場合、テーブルとカラムの名前から指定されます。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).

コマンド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'); uniqueキー追加Adds a unique index.
$table->index('state');$table->index('state'); 基本的なインデックス追加Adds a plain index.
$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を使用している場合、マイグレーションにより生成されるデフォルトのインデックス用文字列長を明示的に設定する必要があります。AppServiceProvider中でSchema::defaultStringLengthを呼び出してください。Laravel uses the utf8mb4 character set by default, which includes support for storing "emojis" in the database. 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 this by calling the Schema::defaultStringLength method within your AppServiceProvider:

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

インデックス名を変更するためには、renameIndexメソッドを使用します。このメソッドは最初の引数として現在のインデックス名を受け取り、2つ目の引数として変更後の名前を受け取ります。To rename an index, you may use the renameIndex method. 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 a reasonable name to the indexes. Concatenate 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 key type:

Schema::table('geo', function (Blueprint $table) {
    $table->dropIndex(['state']); // '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:

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

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

さらに束縛に対して「デリート時(on delete)」と「更新時(on update)」に対する処理をオプションとして指定できます。You may also specify the desired action for the "on delete" and "on update" properties of the constraint:

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

外部キーを削除するには、dropForeignメソッドを使用します。他のインデックスで使用されるものと似た命名規則が、外部キーにも使用されています。つまりテーブル名とカラム名をつなげ、"\_foreign"を最後につけた名前になります。To drop a foreign key, you may use the dropForeign method. Foreign key constraints use the same naming convention as indexes. So, we will concatenate the table name and the columns in the constraint then suffix the name with "_foreign":

$table->dropForeign('posts_user_id_foreign');

もしくは配列値を渡せば、削除時に自動的に命名規則に従った名前が使用されます。Or, you may pass an array value which will automatically use the conventional constraint name when dropping:

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

以下のメソッドにより、マイグレーション中の外部キー制約の有効/無効を変更できます。You may enable or disable foreign key constraints within your migrations by using the following methods:

Schema::enableForeignKeyConstraints();

Schema::disableForeignKeyConstraints();

Note: note デフォルト状態では、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.

章選択

設定

明暗テーマ
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に保存してある設定項目をすべて削除し、デフォルト状態へ戻します。

ヘッダー項目移動

キーボード操作