Add new column to existing table using migration in Laravel

Add new column to existing table using migration in Laravel

To add a new column to an existing table using migration in Laravel, you can follow these steps:

  • Create a new migration file using the php artisan make:migration command. You should give it a descriptive name and specify the table you want to modify using the –table option. For example, if you want to add a new column called status to the users table, you can run this command:
php artisan make:migration add_status_to_users_table --table=users
  • Edit the migration file that was generated in the database/migrations directory. You should use the Schema::table() method to access the existing table, and then use the $table object to add the new column. You can specify the data type, name, and other attributes of the new column.
  • For example, if you want to add a string column called status that is nullable and has a default value of ‘active’, you can write this code:
public function up()
{
Schema::table('users', function (Blueprint $table) {
$table->string('status')->nullable()->default('active');
});
}
  • Don’t forget to add the corresponding code to drop the new column in the down() method of the migration file. This method is used to revert the changes made by the migration in case you need to roll back. For example, you can write this code:
public function down()
{
Schema::table('users', function (Blueprint $table) {
$table->dropColumn('status');
});
}

After that run the command :

php artisan migrate

In case you want to undo the last migration for any reason, run this command :

php artisan migrate:rollback