Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel 4.2 Migrations - Alter decimal precision and scale without dropping column

I wish to increase decimal precision and scale for a decimal column.

I am aware that I can drop the column, and re-create it, but doing so will mean losing the data in the column.

Is there a way using Laravel Schema::table that I can alter the precision and scale of the column without dropping it?

e.g. something like:

Schema::table('prices', function(Blueprint $t) {
    $t->buy_price->decimal(5,2);
});
like image 325
Gravy Avatar asked Jan 21 '26 10:01

Gravy


2 Answers

this worked for me:

public function up()
{
    Schema::table('prices', function(Blueprint $t) {
        $t->decimal('buy_price', 5, 2)->change();
    });
}

when rolling back use original precision values of 3, 1 instead

public function down()
{
    Schema::table('prices', function(Blueprint $t) {
        $t->decimal('buy_price', 3, 1)->change();
    });
}

I avoid DB specific "raw" statements as they might fail when I change to another DBMS engine. So I let Laravel handle necessary syntax when working w/DB

like image 178
Max D. -- Stand with Ukraine Avatar answered Jan 23 '26 22:01

Max D. -- Stand with Ukraine


Just create another migration and in the up method add following code:

public function up()
{
    // Change db_name and table_name
    DB::select(DB::raw('ALTER TABLE `db_name`.`table_name` CHANGE COLUMN `buy_price` `buy_price` decimal(10,2) NOT NULL;'));

}

Also in the down method just set the old value so you can roll-back:

public function down()
{
    // Change db_name and table_name
    DB::select(DB::raw('ALTER TABLE `db_name`.`table_name` CHANGE COLUMN `buy_price` `buy_price` decimal(5,2) NOT NULL;'));

}

Then migrate as usual from the terminal/command prompt using php artisan migrate.

like image 45
The Alpha Avatar answered Jan 23 '26 23:01

The Alpha