Home > Back-end >  Laravel: Running a database migration on a production server
Laravel: Running a database migration on a production server

Time:07-06

I have a local repo for development and a production server in Laravel.

When I work locally, as the project grows, so does the DB. Therefore I keep adding new migrations that sometimes change existing tables. Locally I can refresh / recreate tables and seed without worrying.

However when I want to update the production DB where actual data is stored, what's the best method? If I need to update an existing table I cannot just drop and recreate it, as data would be lost. And if I run the migration directly, I get an error like "table already exists". So I end up manually adding the fields in the DB, which I don't think it's the best way to go.

CodePudding user response:

If data already exists and changes to the table structures are necessary, use Schema::table and not Schema::create. Schema::table is comparable to SQL: ALTER TABLE.
for example:

public function up()
{
    Schema::table('tablename', function (Blueprint $table) {
        $table->string('new_column')->nullable();
    });
}

public function down()
{
    Schema::table('tablename', function (Blueprint $table) {
        $table->dropColumn('new_column');
    });
}

CodePudding user response:

As already mentioned, you can create migrations to update the columns without dropping the tables. And the 'Modifying columns' docs provide a clear explanation for this. However that is docs for modifying columns, if you want to modify tables instead of columns, you can use the 'Updating tables' docs

This uses the SchemaBuilder to do various things, for example, adding columns in an existing table:

Schema::table('table_name'), function ($table) {
  $table->string('new_column')->after('existing_column');
  // however you can leave the ->after() part out, this just specifies that the
  // new column should be insterted after the specified column.
});

Or delete a column from an existing table

Schema::table('table_name'), function ($table) {
  $table->dropColumn('new_column');
});

You can also rename but I'll leave it to you to explore the docs further.

  • Related