Migrations

Make a migration

Migrations are versioned instructions for building tables. Each migration file has a timestamped name, so the team applies them in the same order.

Generate a posts table migration

php artisan make:migration create_posts_table

INFO Migration file created in database/migrations.

Open the new file in database/migrations. It contains empty up and down methods waiting for your schema.

Schema builder

The up method describes the table to create, and the down method describes how to remove it. The Schema builder turns that description into SQL for any supported database.

The posts table below gets an auto-incrementing id, a title column, and timestamp columns for creation and update times.

use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; return new class extends Migration { public function up(): void { Schema::create("posts", function (Blueprint $table) { $table->increments("id"); $table->string("title"); $table->timestamps(); }); } public function down(): void { Schema::dropIfExists("posts"); } };

Run it

The migrate command applies every migration that has not run yet. Laravel records the batch in a migrations table, so re-running the command is safe.

Apply pending migrations

php artisan migrate

INFO Running migrations. create_posts_table done.

Roll back

The rollback command undoes the last batch by calling each down method. Use it right after a bad migration, while the mistake is still fresh and local.

Fix the migration file after rolling back, then migrate again. Never edit migrations that already ran on a shared server.

Undo the last batch

php artisan migrate:rollback

INFO Rolling back migrations. create_posts_table rolled back.

Next: Eloquent models

Article author: Arthur Isaev