How to change column in Laravel migration?

by darrion.kuhn , in category: PHP Frameworks , 9 months ago

How to change column in Laravel migration?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by larissa , 3 months ago

@darrion.kuhn 

To change a column in a Laravel migration, you can use the change method on the Blueprint class in your migration file.


Here's an example of how you can use the change method to modify a column:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
use IlluminateDatabaseMigrationsMigration;
use IlluminateDatabaseSchemaBlueprint;
use IlluminateSupportFacadesSchema;

class ChangeColumnInTable extends Migration
{
    public function up()
    {
        Schema::table('table_name', function (Blueprint $table) {
            $table->string('column_name')->nullable()->change();
        });
    }

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


In this example, we are changing the column_name column in the table_name table to be nullable. The up method is run when you execute the migration, and the down method is run when you rollback the migration.


You can also use the change method to modify other column attributes, such as the column type or default value. For example:

1
$table->integer('column_name')->default(0)->change();


This will change the column_name column to be of type integer and set its default value to 0.


I hope this helps! Let me know if you have any questions.