skip to Main Content

One of my team members added some columns to the production database table using phpMyAdmin. Afterwards I saw that the data wasn’t matching so i decided to create the migration files for the new columns. Now when I try to run php artisan migrate in the production environment I am getting duplicate column error because the columns already exist in the database. How can I handle this problem in Laravel?

I have considered removing the columns manually from the database and then running the migrations but this may result in data loss.

Is there any way to modify the migration without dropping the existing columns?

2

Answers


  1. You could use hasColumn.

      public function up()
        {
            if (!Schema::hasColumn('table_name', 'column_name'))
            {
                Schema::table('table_name', function (Blueprint $table)
                {
                    $table->string('column_name');
                });
            }
        }
    

    More information on the document

    Login or Signup to reply.
  2. you can check in your migration file

    <?php
    use IlluminateDatabaseMigrationsMigration;
    use IlluminateDatabaseSchemaBlueprint;
    use IlluminateSupportFacadesSchema;
    
    class AddNewColumnToMyTable extends Migration
    {
        public function up()
        {
            Schema::table('my_table_name', function (Blueprint $table) {
                if (!Schema::hasColumn('my_table_name', 'new_column')) {
                    $table->string('new_column')->nullable();
                }
            });
        }
    
        public function down()
        {
            Schema::table('my_table_name', function (Blueprint $table) {
                $table->dropColumn('new_column');
            });
        }
    }
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search