lewis4u
lewis4u

Reputation: 15017

Laravel - How to change column type (smallInteger => string)

The documentation doesn't say anything about changing data type with migrations.

I have this column in my DB table

$table->smallInteger('driverslicensetype')->nullable();

and I am saving four-digit numbers, but when the number begins with 0 (a zero) for example 0230 it will be saved as 230 in DB. And that is wrong.

Now i want to change this column data type from smallInteger to varchar.

How can i do this through migrations?

Upvotes: 2

Views: 2737

Answers (1)

bishop
bishop

Reputation: 39354

To use the schema changing feature, you need Doctrine DBAL:

composer require doctrine/dbal

Now you can use change():

public function up()
{
    Schema::table('foo', function (Blueprint $table) {
        $table->string('driverlicensetype', 4)->nullable()->change();
    });
}

public function down()
{
    Schema::table('foo', function (Blueprint $table) {
        $table->smallInteger('driverlicensetype')->nullable()->change();
    });
}

If you prefer the raw approach (or if your SQL is more restrictive, like when driverlicensetype is a foreign key), use DB::statement:

public function up()
{
    DB::statement('ALTER TABLE foo ...');
}
// ...

Upvotes: 2

Related Questions