php - how to set default laravel migration from other tables dynamicly

i have table with two column amount_1 and amount_2 and i have column name real_price and i want to set default value for real_price in database to divide amount_1 to amount_2 and save i try this in migration like below but it fails

            $table->double('real_price')->default('abs(`amount_1`) / greatest(abs(`amount_2`),1)');

error i get after run migrations

Syntax error or access violation: 1067 Invalid default value for 'real_price'

is there any way to this in migration file ?

Answer

Solution:

Mysql and Postgresql do not allow to set calculated values by default

You can do the following:

public function up(): void
{
    Schema::table('my_table', static function (Blueprint $table) {
        $table->double('real_price');
    });

    DB::table('my_table')->update([
        'real_price' => DB::raw('abs(`amount_1`) / greatest(abs(`amount_2`),1)'),
    ]);
}

And to further set the value of real_price, you can use Observers

Source