Isuru Rodrigo
Isuru Rodrigo

Reputation: 85

Change the datatype in the column with data in laravel migration

This is the migration? i have to change the string data column into integer data column with existing data

public function up()
{
       Schema::table('SYS_tenants' ,function (Blueprint $table){
           $table->integer('tena_type')->unsigned()->nullable()->change();
           $table->foreign('tena_type')->references('id')->on('account_types');
       });
}

Upvotes: 1

Views: 4161

Answers (4)

Isuru Rodrigo
Isuru Rodrigo

Reputation: 85

I already use this Laravel Migration

$table->integer('tena_type')->unsigned()->nullable()->change();

But it doesn't work because, the data already in the table. In that case it can't change the datatype.I use this DB statement to change the datatype with data.it's working properly.

DB::statement("alter table SYS_tenants modify tena_type integer not null"):

Upvotes: 1

rattybag
rattybag

Reputation: 421

Migrations#Modifying Columns

Looks like what you have should work:

Schema::table('SYS_tenants' ,function (Blueprint $table){
    $table->integer('tena_type')->unsigned()->nullable()->change();
});

Depending on your database you may need to cast the values to the new type: (for mysql: https://www.mysqltutorial.org/mysql-cast/)

Upvotes: 0

Sehdev
Sehdev

Reputation: 5662

As per laravel Documentation you can create a new migration and do it like this:

Schema::table('SYS_tenants', function (Blueprint $table) {
   $table->integer('tena_type')->unsigned()->nullable()->change();
});

Before modifying a column, be sure to add the doctrine/dbal dependency to your composer.json file.

composer require doctrine/dbal

Reference: Laravel -> Database: Migrations-> Modifying Columns

Upvotes: 3

Yves Kipondo
Yves Kipondo

Reputation: 5603

You can use change method on the field which you want to change the type after setting the new field type.

public function up() {
    Schema::table('SYS_tenants' ,function (Blueprint $table){

        $table->string('tena_type')->change();   
    });
}

I supposed the migration which create the table has already call all requirement you need like unique, nullable and so on. You can call change method, by the way there isn't restriction about any modification you want to perform like add other mysql index on that field.

Do not forget to add doctrine/dbal in composer.json file

Upvotes: 0

Related Questions