Search code examples
laravelmigration

rename column in laravel using migration


I use laravel 5.6

I want to change author_ID to user_id

I have columns as mentioned below:

class CreatePostsTable extends Migration{

    public function up()
    {
        Schema::create('posts', function (Blueprint $table) {
            $table->increments('id');
            $table->bigInteger('author_ID');
            $table->text('title');
            $table->timestamps();
        });
    }

    public function down()
    {
        Schema::dropIfExists('posts');
    }
}

I use the below link to change my column name :

How can I rename a column in laravel using migration?

then create blow migration :

php artisan make:migration rename_author_id_in_post_table

rename migration file :

class UpdateUsernameInPostTable extends Migration{

    public function up()
    {
        Schema::create('posts', function (Blueprint $table) {
            $table->renameColumn('author_ID', 'user_id');
        });

    }

    public function down()
    {
        Schema::create('posts', function (Blueprint $table) {
            $table->renameColumn('user_id', 'author_ID');
        });
    }
}

but with the run command : php artisan migrate I have the below error :

Symfony\Component\Debug\Exception\FatalThrowableError  : 
Class 'RenameAuthorIdInPostTable' not found

Solution

  • Just try this code after deleting your existing migration for updating name,

    php artisan make:migration rename_author_id_in_posts_table --table=posts
    

    It will create one migration and then replace up() and down() functions with this in that created migration,

    public function up()
    {
        Schema::table('posts', function (Blueprint $table) {
            $table->renameColumn('author_ID', 'user_id');
        });
    }
    

    And down() function with this,

    public function down()
    {
        Schema::table('posts', function (Blueprint $table) {
            $table->renameColumn('user_id', 'author_ID');
        });
    }
    

    For more information about migration, you can go through this link Laravel Migrations.

    PROBLEM WITH YOUR MIGRATION:

    You are using Schema::create() method for change in table, As you have already created migration for posts table,You don't need to do Schema::create() just use Schema::table() method to update and change in any fields.

    Schema::create('posts', function (Blueprint $table) {
            $table->renameColumn('author_ID', 'user_id');
        });