Home » Laravel: Change Column Name In Migration

Laravel: Change Column Name In Migration

Last updated on May 31, 2021 by

At some level of project creation, you might want to change the column name in Laravel migration. In this, article we will see the steps to change the column name in Laravel migration. Let’s just dive into it.

Change Column Name In Laravel Migration

The Laravel provides the renameColumn('old column', 'new column') method to change the column name. Let’s take a simple example.

Let’s create a new migration for users table and then we will change any column name into it for better understanding.

php artisan make:migration create_users_table

The above command will create a new migration in database/migrations directory. We have added the following code into the newly created migration.

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateUsersTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->id();
            $table->uuid('uuid')->unique();
            $table->text('title')->nullable();
            $table->text('first_name');
            $table->text('last_name');
            $table->string('email')->unique();
            $table->string('password')->nullable();
            $table->text('gender')->nullable();        
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('users');
    }
}

Now, let’s migrate the database using php artisan migrate command and the users table will be created into our database.

Let’s suppose, now we want to rename the gender column to sex. To do that we need to follow the following steps:

  1. First and most important thing is to check whether or not your project has doctrine/dbal library, if not then please install it first by running the following command:
composer require doctrine/dbal
  1. Create new migration file to update the column
php artisan make:migration update_users_table --table="users"

A new migration file will be created into the database/migrations directory.

  1. Let’s now rename the gender column to sex in the up() method and don’t forget to add the reverse effect from sex to gender in down() method.

    The up() method will be executed when we run the php artisan migrate command and the down() method will be executed when we run the php artisan migrate:rollback command. Thus, you can balance between the migrate and rollback command.
<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class UpdateUsersTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('users', function (Blueprint $table) {
            $table->renameColumn('gender', 'sex');
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::table('users', function (Blueprint $table) {
            $table->renameColumn('sex', 'gender');
        });
    }
}

  1. Finally, run the migrate command to update the table.
php artisan migrate

Rename Foreign Key Column In Laravel Migration

If you follow the above steps to rename foreign key column then it might produce the error because to rename foreign key, we need to handle it differently.

Let’s suppose, posts table has the client_id a foreign key column which references to users table but to follow Laravel’s naming convention we want to rename it to the user_id.

To do that first we need to drop the foreign key of client_id column then rename it to user_id and then we again need to re-assign the foreign key to the user_id column. And never forget to add the reverse effect in the down() method to support rollback command. Let’s just do it.

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class UpdatePostsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('posts', function (Blueprint $table) {
            // Drop foreign key 
            $table->dropForeign(['client_id']);

            // Rename client_id to user_id
            $table->renameColumn('client_id', 'user_id');

            // Re-assign foreign key to user_id
            $table->foreign('user_id')->references('id')->on('users');
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::table('posts', function (Blueprint $table) {
            // Drop foreign key 
            $table->dropForeign(['user_id']);

            // Rename user_id to client_id
            $table->renameColumn('user_id', 'client_id');

            // Re-assign foreign key to client_id
            $table->foreign('client_id')->references('id')->on('users');
        });
    }
}

Additionally, read our guide:

  1. Base Table Or View Already Exists In Laravel Migration
  2. Add Column After A Column In Laravel Migration
  3. Specified Key Was Too Long Error In Laravel
  4. AJAX PHP Post Request With Example
  5. How To Use The Laravel Soft Delete
  6. How To Add Laravel Next Prev Pagination
  7. Laravel Remove Column From Table In Migration
  8. Difference Between Factory And Seeders In Laravel
  9. Laravel: Increase Quantity If Product Already Exists In Cart
  10. How To Calculate Age From Birthdate
  11. How To Check Laravel PHP Version
  12. How To Handle Failed Jobs In Laravel
  13. How To Remove WooCommerce Data After Uninstall
  14. How To Get Latest Records In Laravel
  15. How To Break Nested Loops In PHP Or Laravel
  16. How To Pass Laravel URL Parameter
  17. Laravel Run Specific Migration

That’s it from our end. We hope this article helped you to learn how to change column names and rename foreign key columns in Laravel migration.

Please let us know in the comments if everything worked as expected, your issues, or any questions. If you think this article saved your time & money, please do comment, share, like & subscribe. Thank you for reading this post 🙂 Keep Smiling! Happy Coding!

 
 

Leave a Comment

*

code