Backend Development 5 min read

Master Laravel Database Migrations: Step-by-Step Guide

This article explains how Laravel's database migration system works, covering configuration, creating migration files, designing schemas with the Schema builder, and executing migrations and rollbacks via Artisan commands to efficiently manage and version‑control database structures.

Python Programming Learning Circle
Python Programming Learning Circle
Python Programming Learning Circle
Master Laravel Database Migrations: Step-by-Step Guide

Laravel's database migrations define a unified interface for creating and maintaining database schemas, independent of the underlying DB engine.

Migration files are PHP scripts stored in database/migrations and are executed via Artisan commands from the project root.

1. Configure the database

Set connection details in .env (overriding config/database.php ) such as DB_HOST, DB_DATABASE, DB_USERNAME, and DB_PASSWORD.

2. Create a migration file

Run php artisan make:migration create_tableName_table . The file is named with a UTC timestamp prefix, e.g., 2023_10_12_000000_create_users_table.php , and contains up() and down() methods.

3. Design the migration

Use the Schema builder inside up() to define tables, columns, indexes, etc. Example:

<code>public function up()
{
    Schema::create('users', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->string('account', 32)->unique();
        $table->string('name', 32);
        $table->string('password', 60);
        $table->rememberToken();
        $table->unsignedInteger('created_at');
        $table->tinyInteger('state')->unsigned()->default(1);
    });
}

public function down()
{
    Schema::dropIfExists('users');
}
</code>

The example image illustrates the generated migration file.

4. Run the migration

Execute php artisan migrate to create the tables, or php artisan migrate:rollback to revert them.

By repeating these steps you can manage complex schemas, version‑control multiple tables across several migration files.

backend developmentPHPdatabase migrationLaravelArtisanSchema Builder
Python Programming Learning Circle
Written by

Python Programming Learning Circle

A global community of Chinese Python developers offering technical articles, columns, original video tutorials, and problem sets. Topics include web full‑stack development, web scraping, data analysis, natural language processing, image processing, machine learning, automated testing, DevOps automation, and big data.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.