Home > Enterprise >  How can i add new column to the all exesting tables in laravel migrations
How can i add new column to the all exesting tables in laravel migrations

Time:09-16

I have an existing project and now I have to add a new column to all the existing, I have no idea how can I achieve that in Laravel migrations

CodePudding user response:

php artisan make:migration add_columnname_to_tablename_table --table=tablename

in tour file

public function up()
    {
        Schema::table('tablename', function (Blueprint $table) {
            $table->datatype('newcolumnname')->nullable();
        });
    }
public function down()
{
    Schema::table('tablename', function($table) {
        $table->dropColumn('newcolumnname');
    });
}

Run

php artisan migrate

CodePudding user response:

Suppose you want to add column newcolumnname to table tablename. First create the migration file:

php artisan make:migration add_newcolumnname_to_tablename --table="tablename"

Then in the up function of the generated migration file:

public function up()
{
    Schema::table('tablename', function($table) {
        $table->text('newcolumnname'); //suppose the datatype is text
    });
}

If you want to do this to multiple tables, for the artisan command, you could:

php artisan make:migration add_singlecolumn_to_tables

For the up function, you could:

public function up()
{
    $tables=['table1','table2','table3']; //DB::select('SHOW TABLES'); 
    for($i=0;$i<count($tables);$i  ){
        Schema::table($tables[$i], function (Blueprint $table) {
            $table->text('test_column')->nullable();    //suppose the datatype is text
        });
    }
    
}

CodePudding user response:

just use :

php artisan make:migration new_column_table

at database/migrations/[datetime]_new_column_table.php

public function up() {
    Schema::table('table_a', function(Blueprint $table) {
        $table->text('new_column')->nullable();
    });
    
    Schema::table('table_a', function(Blueprint $table) {
        $table->text('new_column')->nullable();
    });
    
    Schema::table('table_c', function(Blueprint $table) {
        $table->text('new_column')->nullable();
    });
}

public function down()
{
    Schema::table('table_a', function (Blueprint $table) {
        $table->dropColumn('new_column');
    });
    
    Schema::table('table_b', function (Blueprint $table) {
        $table->dropColumn('new_column');
    });
    
    Schema::table('table_c', function (Blueprint $table) {
        $table->dropColumn('new_column');
    });
}
  • Related