0
0
LaravelHow-ToBeginner · 3 min read

How to Create Migration in Laravel: Step-by-Step Guide

To create a migration in Laravel, run the php artisan make:migration migration_name command in your terminal. This generates a migration file in the database/migrations folder where you define your database schema changes.
📐

Syntax

The basic syntax to create a migration in Laravel is:

  • php artisan make:migration migration_name: Creates a new migration file with the given name.
  • The migration file is saved in database/migrations directory.
  • Inside the migration file, you define up and down methods to apply or rollback schema changes.
bash
php artisan make:migration create_users_table
💻

Example

This example creates a migration to add a users table with id, name, email, and timestamps columns.

php
<?php

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

return new class extends Migration {
    public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->string('email')->unique();
            $table->timestamps();
        });
    }

    public function down()
    {
        Schema::dropIfExists('users');
    }
};
Output
Migration file created in database/migrations and ready to run with php artisan migrate
⚠️

Common Pitfalls

  • Forgetting to run php artisan migrate after creating the migration means changes won't apply.
  • Using invalid table or column names can cause errors.
  • Not defining the down method properly prevents rollback.
  • Running migration commands outside the Laravel project folder will fail.
bash
Wrong:
php artisan make:migration users

Right:
php artisan make:migration create_users_table
📊

Quick Reference

CommandDescription
php artisan make:migration migration_nameCreate a new migration file
php artisan migrateRun all pending migrations
php artisan migrate:rollbackUndo the last batch of migrations
php artisan migrate:statusShow migration status

Key Takeaways

Use php artisan make:migration migration_name to create migration files.
Define schema changes inside the up method and rollback logic in down.
Always run php artisan migrate to apply migrations to the database.
Name migrations clearly to describe their purpose, like create_users_table.
Check migration status with php artisan migrate:status to track applied migrations.