Home Arrow Icon Knowledge base Arrow Icon Global Arrow Icon Laravel migration change column default value
    Laravel migration change default value Laravel database column default value Laravel schema PHP artisan


Laravel migration change column default value


Here's how you can change the default value of a column in a Laravel migration:

1. Create a new migration:


   php artisan make:migration change_default_value_in_tasks_table
   

This will create a new migration file in the `database/migrations` directory.

2. Update the `up()` method:

php
   public function up()
   {
       Schema::table('tasks', function (Blueprint $table) {
           $table->integer('priority')->default(2)->change();
       });
   }
   

In the `up()` method, we use the `$table->change()` method to modify the existing `priority` column's default value from its current value to `2`.

3. Update the `down()` method:

php
   public function down()
   {
       Schema::table('tasks', function (Blueprint $table) {
           $table->integer('priority')->default(null)->change();
       });
   }
   

In the `down()` method, we revert the changes by changing the `priority` column's default value back to `null`.

4. Run the migration:


   php artisan migrate
   

This will apply the changes to the database.

The key points are:

- Use the `$table->change()` method to modify the existing column's default value.
- Specify the new default value in the column definition (e.g., `$table->integer('priority')->default(2)`).
- Provide a `down()` method to revert the changes, if needed.
- Make sure to install the `doctrine/dbal` package before running the migration.

This approach allows you to change the default value of a column in your database schema while preserving the existing data. Remember to thoroughly test your migrations before running them in a production environment.

Citations:
[1] https://www.itsolutionstuff.com/post/laravel-migration-change-default-value-exampleexample.html
[2] https://www.itsolutionstuff.com/post/how-to-add-default-value-of-column-in-laravel-migrationexample.html
[3] https://laraveldaily.com/post/two-ways-to-set-default-db-column-values-in-laravel
[4] https://stackoverflow.com/questions/37003469/laravel-migrations-change-default-value-of-column
[5] https://laravel.io/forum/strategy-for-multi-change-migrations