Add column name or change column properties
Sometimes we want to perform additional changes in the column of table such as renaming, adding extra column and changing the attributes of predefined column. There are two ways to perform these :
1. Simply made changes in the existing migration file. Check the below example:
Say my old migration file has the below mentioned fields.
public function up()
{
Schema::create('products', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('category');
$table->timestamps();
});
}
Suppose I want to add one more column ‘description’ in the table. Then just add column in the existing migration as shown below:
public function up()
{
Schema::create('products', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('category');
$table->string('description');
$table->timestamps();
});
}
After that run command “php artisan run migrate:fresh“. But use this command carfully. From my point of view it would be better to use this command in the initial stages of creating database. Like you have just started creating database structure and it is empty. Because this command generally drop all tables from database and then run migrate command.
2. Second way is create another migration, specify changes in it and then execute it. See how ??
Schema::table('users', function (Blueprint $table) {
$table->string('name');
});
Say I want to modify the ‘name
‘ to ‘username’. Then create migration and name it in the way so that when you read out in the future it will gave you its purpose at first glance. So I will create as:
php artisan make:migration modify_col_name --table=users
Schema::table('users', function (Blueprint $table) {
$table->renameColumn('name', 'username');
}
This renameColumn() will work if you have installed doctrine/dbal library. So run the below composer command.
composer require doctrine/dbal
After making possible changes in the file then finally execute “php artisan migrate” command.
Now if we want to modify its properties like specifying size for the username values. Then add further code as mentioned below:
Schema::table('users', function (Blueprint $table) {
$table->renameColumn('name', 'username');
});
Schema::table('users', function (Blueprint $table) {
$table->string('username',80)->change();
});