SyntaxStudy
Sign Up
Laravel Altering Tables and Running Migrations
Laravel Beginner 1 min read

Altering Tables and Running Migrations

Modifying an existing table is done by creating a new migration and using Schema::table() instead of Schema::create(). The change() method modifies an existing column's type or modifiers. Renaming columns uses renameColumn(), dropping them uses dropColumn(). The doctrine/dbal package was historically required for these operations but is no longer needed as of Laravel 10. Migration commands offer fine-grained control. php artisan migrate:status lists which migrations have run. php artisan migrate:fresh drops all tables and reruns all migrations from scratch — useful during development. php artisan migrate:refresh rolls back all migrations and re-runs them. The --seed flag can be appended to any migrate command to run database seeders afterwards. Squashing migrations with php artisan schema:dump collapses all existing migrations into a single SQL dump file, keeping the migrations folder clean on mature projects. The dump is loaded first when running php artisan migrate on a fresh database, followed by any migrations created after the squash. This dramatically reduces migration execution time on CI pipelines.
Example
<?php
// database/migrations/2024_06_01_000001_add_views_to_posts_table.php

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::table('posts', function (Blueprint $table) {
            // Add new columns
            $table->unsignedBigInteger('view_count')->default(0)->after('status');
            $table->string('featured_image')->nullable()->after('body');

            // Modify an existing column (requires nullable change)
            $table->string('slug', 300)->change();

            // Add a new index
            $table->index('view_count');
        });
    }

    public function down(): void
    {
        Schema::table('posts', function (Blueprint $table) {
            $table->dropIndex(['view_count']);
            $table->dropColumn(['view_count', 'featured_image']);
        });
    }
};

// Terminal commands:
// php artisan migrate                 — run pending migrations
// php artisan migrate:rollback        — roll back the last batch
// php artisan migrate:rollback --step=3
// php artisan migrate:fresh --seed    — drop all + migrate + seed
// php artisan migrate:status          — show migration status