Laravel Migrations

Laravel Migrations

Migrations are version control for your database. They allow you to define and share the application's database schema.

1 - Creating a Migration

php artisan make:migration create_posts_table
php artisan make:migration add_published_at_to_posts_table --table=posts

2 - Writing a Migration

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->id();
            $table->foreignId('user_id')->constrained()->cascadeOnDelete();
            $table->string('title');
            $table->string('slug')->unique();
            $table->longText('body');
            $table->boolean('published')->default(false);
            $table->timestamp('published_at')->nullable();
            $table->timestamps();
        });
    }

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

3 - Running Migrations

php artisan migrate            // Run pending migrations
php artisan migrate:rollback   // Rollback last batch
php artisan migrate:fresh      // Drop all tables and re-run
php artisan migrate:status     // Show migration status

4 - Common Column Types

$table->string('name', 100);    // VARCHAR(100)
$table->text('bio');            // TEXT
$table->integer('views');       // INT
$table->decimal('price', 8, 2); // DECIMAL(8,2)
$table->boolean('active');      // TINYINT(1)
$table->json('metadata');       // JSON
$table->enum('status', ['draft', 'published']);
$table->foreignId('user_id')->constrained();
$table->softDeletes();          // deleted_at column