Advertisement

Google Ad Slot: content-top

Laravel Modify Table


Modify Table Migration

Use this command to generate a migration for creating a table:

php artisan make:migration add_status_verified_to_posts_table


This generates a file in database/migrations/:

public function up(): void
{
    Schema::table('posts', function (Blueprint $table) {
        $table->string('status')->default('draft');
        $table->timestamp('verified_at')->nullable();
    });
}

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


Running Migrations:

php artisan migrate
Output: posts table
Before Modify table
Name Type
id bigint(20)
title varchar(255)
content text
created_at timestamp
updated_at timestamp
After Modify table
Name Type
id bigint(20)
title varchar(255)
content text
created_at timestamp
updated_at timestamp
status varchar(255)
verified_at timestamp

Renaming Columns

Rename column title -> username

public function up(): void
{
    Schema::table('posts', function (Blueprint $table) {
        $table->renameColumn('title', 'username');
    });
}

public function down(): void
{
    Schema::table('posts', function (Blueprint $table) {
        $table->renameColumn('username', 'title');
    });
}

Changing Column Types or Attributes

To change a column type or add modifiers (like making a column nullable):

public function up(): void
{
    Schema::table('users', function (Blueprint $table) {
      $table->string('email', 500)->nullable()->change();
    });
}

public function down(): void
{
    Schema::table('users', function (Blueprint $table) {
      $table->string('email', 255)->nullable(false)->change();
    });
}