[php] How can I rename column in laravel using migration?

I have columns as mentioned bellow:

public function up()
{
    Schema::create('stnk', function(Blueprint $table)
    {
        $table->increments('id');
        $table->string('no_reg', 50)->unique();
        $table->string('no_bpkb', 50)->unique();
        $table->string('nama_pemilik', 100);
        $table->string('alamat');
        $table->string('merk', 50);
        $table->string('tipe', 50);
        $table->string('jenis', 50);
        $table->smallInteger('tahun_pembuatan');
        $table->smallInteger('tahun_registrasi');
        $table->smallInteger('isi_silinder');
        $table->string('no_rangka', 50);
        $table->string('no_mesin', 50);
        $table->string('warna', 50);
        $table->string('bahan_bakar', 50);
        $table->string('warna_tnkb', 50);
        $table->string('kode_lokasi', 50);
        $table->date('berlaku_sampai');
        $table->timestamps();

        $table->index('created_at');
        $table->index('updated_at');
    });

}

I have made seeder to stnk table

Now I want to rename id to id_stnk.
I've added a "doctrine / dbal" in the "composer" and do a composer update.

I've made migration php artisan migration:make rename_column.
Then I've added new method to rename_column:

Schema::table('stnk', function(Blueprint $table)
{
    $table->renameColumn('id', 'id_stnk');

});

And then I've tried to run command php artisan migrate but I got error as mentioned bellow:

[Ulluminate\Database\QueryException]
SQLSTATE[HY000]: General error: 1025 Error on rename of './my_database/#sql -447_33' to './my_database/stnk' (error: 150) (SQL: ALTER TABLE stnk CHANGE id id_stnk INT UNSIGENED AUTO_INCREMENT NOT NULL)

[PDOException]
SQLSTATE[HY000]: General error: 1025  Error on rename  of './my_database/#sql -447_33' to './my_database/stnk' (error: 150)

This question is related to php mysql database laravel migration

The answer is


Renaming Columns (Laravel 5.x)

To rename a column, you may use the renameColumn method on the Schema builder. *Before renaming a column, be sure to add the doctrine/dbal dependency to your composer.json file.*

Or you can simply required the package using composer...

composer require doctrine/dbal

Source: https://laravel.com/docs/5.0/schema#renaming-columns

Note: Use make:migration and not migrate:make for Laravel 5.x


Follow these steps, respectively for rename column migration file.

1- Is there Doctrine/dbal library in your project. If you don't have run the command first

composer require doctrine/dbal

2- create update migration file for update old migration file. Warning (need to have the same name)

php artisan make:migration update_oldFileName_table

for example my old migration file name: create_users_table update file name should : update_users_table

3- update_oldNameFile_table.php

Schema::table('users', function (Blueprint $table) {
$table->renameColumn('from', 'to');
});

'from' my old column name and 'to' my new column name

4- Finally run the migrate command

php artisan migrate

Source link: laravel document


You need to create another migration file - and place it in there:

Run

Laravel 4:    php artisan migrate:make rename_stnk_column
Laravel 5:    php artisan make:migration rename_stnk_column

Then inside the new migration file place:

class RenameStnkColumn extends Migration
{

    public function up()
    {
        Schema::table('stnk', function(Blueprint $table) {
            $table->renameColumn('id', 'id_stnk');
        });
    }


    public function down()
    {
        Schema::table('stnk', function(Blueprint $table) {
            $table->renameColumn('id_stnk', 'id');
        });
    }

}

The above answer is great or if it will not hurt you, just rollback the migration and change the name and run migration again.

 php artisan migrate:rollback

Throwing my $0.02 in here since none of the answers worked, but did send me on the right path. What happened was that a previous foreign constraint was throwing the error. Obvious when you think about it.

So in your new migration's up method, first drop that original constraint, rename the column, then add the constraint again with the new column name. In the down method, you do the exact opposite so that it's back to the sold setting.

/**
 * Run the migrations.
 *
 * @return void
 */
public function up()
{
    Schema::table('proxy4s', function (Blueprint $table) {
        // Drop it
        $table->dropForeign(['server_id']);

        // Rename
        $table->renameColumn('server_id', 'linux_server_id');

        // Add it
        $table->foreign('linux_server_id')->references('id')->on('linux_servers');
    });
}

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

        // Rename
        $table->renameColumn('linux_server_id', 'server_id');

        // Add it
        $table->foreign('server_id')->references('id')->on('linux_servers');
    });
}

Hope this saves someone some time in the future!


first thing you want to do is to create your migration file.

Type in your command line

php artisan make:migration rename_stk_column --table="YOUR TABLE" --create

After creating the file. Open the new created migration file in your app folder under database/migrations.

In your up method insert this:

Schema::table('stnk', function(Blueprint $table)
    {
        $table->renameColumn('id', 'id_stnk');
    });
}

and in your down method:

    Schema::table('stnk', function(Blueprint $table)
    {
        $table->renameColumn('id_stnk', 'id);
    });
}

then in your command line just type

php artisan migrate

Then wollah! you have just renamed id to id_stnk. BTW you can use

php artisan migrate:rollback

to undo the changes. Goodluck


I know this is an old question, but I faced the same problem recently in Laravel 7 application. To make renaming columns work I used a tip from this answer where instead of composer require doctrine/dbal I have issued composer require doctrine/dbal:^2.12.1 because the latest version of doctrine/dbal still throws an error.

Just keep in mind that if you already use a higher version, this answer might not be appropriate for you.


Examples related to php

I am receiving warning in Facebook Application using PHP SDK Pass PDO prepared statement to variables Parse error: syntax error, unexpected [ Preg_match backtrack error Removing "http://" from a string How do I hide the PHP explode delimiter from submitted form results? Problems with installation of Google App Engine SDK for php in OS X Laravel 4 with Sentry 2 add user to a group on Registration php & mysql query not echoing in html with tags? How do I show a message in the foreach loop?

Examples related to mysql

Implement specialization in ER diagram How to post query parameters with Axios? PHP with MySQL 8.0+ error: The server requested authentication method unknown to the client Loading class `com.mysql.jdbc.Driver'. This is deprecated. The new driver class is `com.mysql.cj.jdbc.Driver' phpMyAdmin - Error > Incorrect format parameter? Authentication plugin 'caching_sha2_password' is not supported How to resolve Unable to load authentication plugin 'caching_sha2_password' issue Connection Java-MySql : Public Key Retrieval is not allowed How to grant all privileges to root user in MySQL 8.0 MySQL 8.0 - Client does not support authentication protocol requested by server; consider upgrading MySQL client

Examples related to database

Implement specialization in ER diagram phpMyAdmin - Error > Incorrect format parameter? Authentication plugin 'caching_sha2_password' cannot be loaded Room - Schema export directory is not provided to the annotation processor so we cannot export the schema SQL Query Where Date = Today Minus 7 Days MySQL Error: : 'Access denied for user 'root'@'localhost' SQL Server date format yyyymmdd How to create a foreign key in phpmyadmin WooCommerce: Finding the products in database TypeError: tuple indices must be integers, not str

Examples related to laravel

Parameter binding on left joins with array in Laravel Query Builder Laravel 4 with Sentry 2 add user to a group on Registration Target class controller does not exist - Laravel 8 Visual Studio Code PHP Intelephense Keep Showing Not Necessary Error The POST method is not supported for this route. Supported methods: GET, HEAD. Laravel How to fix 'Unchecked runtime.lastError: The message port closed before a response was received' chrome issue? Post request in Laravel - Error - 419 Sorry, your session/ 419 your page has expired Expected response code 250 but got code "530", with message "530 5.7.1 Authentication required How can I run specific migration in laravel Laravel 5 show ErrorException file_put_contents failed to open stream: No such file or directory

Examples related to migration

Want to upgrade project from Angular v5 to Angular v6 Laravel 5.4 Specific Table Migration SQLSTATE[HY000] [2002] Connection refused within Laravel homestead Laravel migration table field's type change How can I rename column in laravel using migration? Warning about `$HTTP_RAW_POST_DATA` being deprecated Entity Framework rollback and remove bad migration Migration: Cannot add foreign key constraint Maven is not working in Java 8 when Javadoc tags are incomplete Rails: Adding an index after adding column