Rename a column in laravel migration

Step 1: Install a Package

composer require doctrine/dbal

Suppose we have a posts table and we want to rename a field or column name.

posts table - before

Here we see the posts table. Now we want to rename column category to category_id.

Step 2: Generate Migration File

Generate a migration file for renaming the column using the artisan command:

php artisan make:migration rename_column_name_in_table_name --table=table_name

As we rename the posts table column category to category_id, the command will be:

php artisan make:migration rename_category_in_posts --table=posts

This command will create a migration file like the one below.

migrations rename field name

This file will create a class in the format RenameColumnNameInTableName and also creates two methods: up and down.

Step 3: Open the Migration File

Click to open the file. In this file our class name will be RenameCategoryInPosts.

rename category in posts

Step 4: Use the renameColumn Method

In the up method:

renameColumn('old_column_name', 'new_column_name')

In the down method:

renameColumn('new_column_name', 'old_column_name')

As we rename column category to category_id, the methods will be:

rename column using laravel migration

Step 5: Run the Migration

Finally, migrate the file using the artisan command:

php artisan migrate
migrating rename column

After migrating, open the database posts table and see the changes.

posts table - after