🎓 A1Learner
🔍
0 of 50 lessons completed

Laravel Migrations

A migration is a PHP class that changes the database structure. A migration creates or changes one table.

Create a migration

The name says which table the migration builds.

php artisan make:migration create_posts_table

Build the table

Three column lines shape the new table.

Schema::create('posts', function (Blueprint $table) {
    $table->id();
    $table->string('title');
    $table->timestamps();
});

Run the migration

The command runs the migration and builds the table.

php artisan migrate

Example

return new class extends Migration
{
    public function up(): void
    {
        Schema::create('posts', function (Blueprint $table) {
            $table->id();
            $table->string('title');
            $table->timestamps();
        });
    }

    public function down(): void
    {
        Schema::dropIfExists('posts');
    }
}

Key points

  • Use php artisan make:migration to create a migration file.
  • Use Schema::create() to build a new table.
  • Use the up method for the change and the down method to undo it.
  • Use timestamps() to add the created_at and updated_at columns.
  • Use php artisan migrate to run the pending migrations.

In this example, the up method builds the posts table. It adds an id, a title and timestamps. The down method drops the table. A migration is a PHP class that changes the database structure.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

Which command runs the pending migrations?