1

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

swatantra
  • 383
  • 1
  • 7
  • 18

3 Answers3

4
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
VIKAS KATARIYA
  • 5,867
  • 3
  • 17
  • 34
2

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
        });
    }
    
}
Phil
  • 1,444
  • 2
  • 10
  • 21
  • it will only add the specified table, is not it??? i want to all the tables i have up to now in my project – swatantra Sep 16 '21 at 04:17
  • Then you may make an array of table name (or get them by `DB::select('SHOW TABLES'); `) and loop through the array. – Phil Sep 16 '21 at 04:21
0

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');
    });
}
uenokazuma
  • 93
  • 6