RedoHub

How to rename a column in laravel migration?


Step 1: First 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 posts table. Now we want to rename column category to catagory_id.

Step 2: Generate migration file for rename column using artisan command.

php artisan make:migration rename_column_name_in_table_name --table=table_name

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

php artisan make:migration rename_category_in_posts --table=posts

This command will be create a migration file like as below.

migrations rename field name

This file will be creating a class in this format RenameColumnNameInTableName and also create two methods up and down.

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

rename category in posts

Step 4: Now rename column using renameColumn method

In up method:

renameColumn('old_column_name', 'new_column name')

In down method:

renameColumn('new_column name', ' new_column name')

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

rename column using laravel migration

Step 5: At last migrate the file using artisan command:

php artisan migrate

Migrating:

migrating rename column

After migrate open the database posts table and see the changes

posts table - after