How to Create a Migration to Change a Column Type in Laravel

How to Create a Migration to Change a Column Type in Laravel

Step 1: Install Doctrine DBAL

Laravel requires the doctrine/dbal package to modify column types. Install it using:

composer require doctrine/dbal

Step 2: Generate the Migration

Run the following command to create a migration file for modifying a column:

php artisan make:migration change_column_type_in_table_name --table=table_name

Step 3: Modify the Migration File

Open the newly created migration file in database/migrations/ and update the up and down methods:

public function up()
{
    Schema::table('table_name', function (Blueprint $table) {
        $table->integer('column_name')->change();
    });
}

public function down()
{
    Schema::table('table_name', function (Blueprint $table) {
        $table->string('column_name')->change();
    });
}

Step 4: Run the Migration

Apply the migration to update the database schema:

php artisan migrate

Step 5: Verify the Changes

Check your database to ensure the column type has been successfully changed.

Conclusion

Congratulations! You have successfully changed a column's data type using Laravel migrations.

0 Comments