-2

Let say I already got a table in my MySQL database, and I want to add columns to it. To do so, I am doing it like the following:

Schema::table('mytable', function($table) {
    $table->integer('my_special_integer')->after('previous_column');
    $table->text('my_special_text')->after('my_special_integer');
    $table->string('my_special_string')->after('my_special_text');
    /*Some many other field*/
    $table->string('my_last_column_to_add')->after('my_second_last_column');
}

Is there a less repeating way if I would simply like to input a bunch of column after a certain previous column?

cytsunny
  • 4,838
  • 15
  • 62
  • 129

3 Answers3

0

No, after() just applies the sql AFTER sql statement.

ALTER TABLE table_name
ADD COLUMN  new_column
AFTER       existing_column
xyzale
  • 745
  • 8
  • 14
0

There isn't a way to do it out of the box, however, what you could do is something like:

$columns = [
        'my_special_integer'    => 'integer',
        'my_special_text'       => 'text',
        'my_special_string'     => 'string',
        'my_last_column_to_add' => 'string',
];

$previous = 'previous_column';

foreach ($columns as $name => $type) {
    $table->$type($name)->after($previous);
    $previous = $name;
}

Hope this helps!

Rwd
  • 34,180
  • 6
  • 64
  • 78
-1

You can use mysql query to alter the column in migration with DB::statement like below

public function up()
{

DB::statement("ALTER TABLE mytable MODIFY COLUMN column_name1 AFTER column_name2");

}
Hariharan
  • 1,174
  • 2
  • 12
  • 17