I want to learn a bit more regarding best practices when it comes to migrations. Usually when we created a new column in our tables we would make use of migrations to create the column and then use the up function to populate the table when the migration executes. But this feels risky because if something goes wrong in the execution of the up function you are unable to use the down function to revert any changes made by the migration.
So for my latest feature I opted to make use of the commands feature to then populate my new column with data. This command only needs to be run once off and from there the system will handle data for that column on create and update actions. But now there will be a manual process on the initial release to run the command via forge. Is this approach better or what would your recommendations be?
Here is an example of my migration and command logic if that gives a clearer picture of what I'm doing
class AddEvalCodesToEvaluationsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
$tableName = 'evaluations';
Schema::table($tableName, function (Blueprint $table) {
$table->string('code', 64)->nullable()->unique()->after('sampleKey');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::table('evaluations', function (Blueprint $table) {
$table->dropColumn('code');
});
}
}
class GenerateEvaluationCodes extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'generate:evaluation-codes';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Generate Evaluation Codes where missing';
/**
* Create a new command instance.
*
* @return void
*/
public function __construct()
{
parent::__construct();
}
/**
* Execute the console command.
*
* @return mixed
*/
public function handle()
{
$this->info('Starting evaluation code generation...');
Evaluation::withTrashed()->chunk(1000, function($evaluations) {
foreach ($evaluations as $evaluation) {
$evaluation->code = $evaluation->generateCode();
$evaluation->save();
}
});
$this->info('Finished generating evaluation codes');
}
}