I have a MySQL database with a table called user_level_attempt. That table has a ENUM type column with ['PROGRESSED', 'STOPPED', 'COMPLETED'] values. I need to write a migration to add another value (let's say 'PASSED') to that column. After adding, it'll look like this, ['PROGRESSED', 'STOPPED', 'COMPLETED', 'PASSED]. How can I do that in Laravel? I tried the following solution but it doesn't seem like a good practice/solution.
/**
* Schema table name to migrate
* @var string
*/
public $set_schema_table = 'bt_user_level_attempt';
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::table($this->set_schema_table, function ($table) {
$table->dropColumn('status');
});
Schema::table($this->set_schema_table, function ($table) {
$table->enum('status', ['PROGRESS', 'STOPPED', 'COMPLETED', 'PASSED'])->default('PROGRESS')->after('effective_time_spend');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::table($this->set_schema_table, function ($table) {
$table->dropColumn('status');
});
Schema::table($this->set_schema_table, function ($table) {
$table->enum('status', ['PROGRESS', 'STOPPED', 'COMPLETED'])->default('PROGRESS')->after('effective_time_spend');
});
}
Thank you.
As per the docs, you just need to create a separate migration to create the new column. This will allow you to add a column without resetting or rolling back your tables, and thus prevent you from losing your data.
Renaming Columns To rename a column, you may use the renameColumn method on the Schema builder. Before renaming a column, be sure to add the doctrine/dbal dependency to your composer. json file: Schema::table('users', function (Blueprint $table) { $table->renameColumn('from', 'to'); });
Enums can't be nullable.
After all, I figure out to find a solution. Thanks to all fellows for enlightening me. :)
/**
* Schema table name to migrate
* @var string
*/
public $set_schema_table = 'bt_user_level_attempt';
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
DB::statement("ALTER TABLE ".$this->set_schema_table." MODIFY COLUMN status ENUM('PROGRESS', 'STOPPED', 'COMPLETED', 'PASSED') NOT NULL DEFAULT 'PROGRESS'");
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
DB::statement("ALTER TABLE ".$this->set_schema_table." MODIFY COLUMN status ENUM('PROGRESS', 'STOPPED', 'COMPLETED') NOT NULL DEFAULT 'PROGRESS'");
}
You should try with DB::statement
method:
Use the DB::statement
method:
DB::statement("ALTER TABLE ".$this->set_schema_table." CHANGE COLUMN status ENUM('PROGRESS', 'STOPPED', 'COMPLETED','PASSED') NOT NULL DEFAULT 'PROGRESS'");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With