Laravelのマイグレーション【現役エンジニアが解説】
今回は、Laravelのマイグレーションについて、簡単に解説していきます。
マイグレーションの作成
マイグレーションではデータベースのテーブルの作成や変更等を行えます。
マイグレーションの作成は、php artisan make:migrationコマンドで可能です。
php artisan make:migration create_users_table
上記の例では、usersというテーブルを作成するためのマイグレーションを作成しています。
マイグレーションファイルの内容
マイグレーションファイルは以下のような内容となっています。
<?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('users', function (Blueprint $table) { $table->id(); $table->string('name'); $table->string('email')->unique(); $table->timestamp('email_verified_at')->nullable(); $table->string('password'); $table->rememberToken(); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('users'); } };
上記の例では、up関数がテーブル作成、down関数がテーブル削除を行う内容となっています。
また、up関数のcreateメソッド内では、$table->型(‘カラム名’)->オプションという形でカラムを追加できます。
マイグレーションの実行
マイグレーションファイルの作成だけではまだデータベースに反映されません。
データベースに反映させるためには、マイグレーションを実行する必要があります。
php artisan migrate
上記のとおり、php artisan migrateコマンドを使って、マイグレーションを実行することができます。