Wutame
Wutame

Reputation: 69

Laravel: Rename table field without deleting data during migration

I'm trying to change "name" into "username" without deleting the existing records.

I tried all of these but it just wipes out the data in the table.

php artisan *
     migrate:fresh       Drop all tables and re-run all migrations
     migrate:install     Create the migration repository
     migrate:refresh     Reset and re-run all migrations
     migrate:reset       Rollback all database migrations
     migrate:rollback    Rollback the last database migration
     migrate:status      Show the status of each migration

Upvotes: 1

Views: 2584

Answers (3)

Vishal Tarkar
Vishal Tarkar

Reputation: 826

For that you have to follow below steps!

1. install Doctrine/dbal

composer require doctrine/dbal

2. create a migration file to rename column name

php artisan make:migration updateTableColumnName

3. add below code to edit your column name

Schema::table('YourTableName', function (Blueprint $table) {
    $table->renameColumn('name', 'username');
});

And Run the migration you have done it without losing your data.

php artisan migrate

Upvotes: 1

Rahul Kathrotiya
Rahul Kathrotiya

Reputation: 112

Step 1 - php artisan make:migration rename_table
Step 2 - Schema::rename('old_table_name', 'new_table_name');
Step 3 - php artisan migrate

Upvotes: 2

Khem Raj Regmi
Khem Raj Regmi

Reputation: 2270

suppose you have 'table_name' table and you want to change column 'old_column_name' to 'new_column_name'

php artian make:migration rename_columns_to_table_name_table --table=table_name

and then,

Schema::table('table_name', function ($table) {
    $table->renameColumn('old_column_name', 'new_column_name');
});

run migration,

php artisan migrate

Upvotes: 0

Related Questions