Reputation: 594
I am using laravel and mysql database ,i want to change the column type and data what ever present inside the database can you please help me to acheive this one..
Schema::table('users', function (Blueprint $table) {
// DB::query("ALTER TABLE `users`.`percentage` CHANGE COLUMN `percentage/100` Decimal(23,4) NUllable ;");
$table->decimal('percentage')->storedAs("'percentage' / 100");
});
Upvotes: 0
Views: 2235
Reputation: 111
Here is official documentation of Laravel regarding this issue : Updating Column Attributes
Upvotes: 0
Reputation: 656
Question: Updating table schema without affecting data in Laravel
For example this is your database migrate file:
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
class CreateUsersTable extends Migration {
public function up()
{
Schema::create('users', function(Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('email');
$table->string('percentage');
$table->timestamps();
});
}
public function down()
{
Schema::drop('users');
}
}
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
class changeColumnUsersTable extends Migration {
public function up()
{
Schema::table('users', function($table)
{
$table->decimal('percentage', 23, 4)->change();
});
}
public function down()
{
Schema::table('users', function($table)
{
$table->decimal('percentage', 23, 4)->change();
});
}
}
Then migrate using the command,
php artisan migrate
Upvotes: 3
Reputation: 4556
In the Laravel Documentation, there's a Updating Column Attributes
But the thing is ->change()
doesn't work with storeAs
, so you may want to use a raw query here:
public function up()
{
DB::statement("ALTER TABLE `users` CHANGE `percentage` `percentage` DECIMAL(23,4) AS (('percentage' / 100)) STORED");
}
Upvotes: 0