Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rearrange columns in a Laravel migration file

How do I re-arrange a column in a Laravel migration file for a MySQL database?

So far I have the following:

$table->date('foo')->after('bar')->change();

However, it does not seem to re-arrange the column.

Why not and how can I fix this?

like image 878
Yahya Uddin Avatar asked Mar 03 '17 10:03

Yahya Uddin


People also ask

How do I change the position of a column in Laravel migration?

use Illuminate\Support\Facades\DB; // This goes inside a migration file DB::statement('ALTER TABLE users MODIFY COLUMN external_id VARCHAR(255) AFTER id'); Those of you paying attention would have picked up that we are redefining the column type ( VARCHAR(255) ), it's a little of an annoyance but it's also required.

How do I add a column to an existing table of Laravel in a migration?

The Laravel migrations will use the Schema facade to create and modify database tables and columns: Schema::create('tasks', function (Blueprint $table) { $table->bigIncrements('id'); $table->timestamps(); }); Inside the facade, you could specify the different columns that you want to add.

How do I change a column to unique in Laravel migration?

$table->unique('slug');


2 Answers

Can't see anything in Laravel Schema API that will allow you to rearrange columns. Your best bet will be to use raw SQL statement as below.

 DB::statement("ALTER TABLE table_name MODIFY COLUMN col_name col_definition AFTER another_col");
like image 101
Silvanus Matiku Avatar answered Oct 11 '22 23:10

Silvanus Matiku


Try this, hope it help you to find right solution:

public function up()
{
    DB::statement("ALTER TABLE example MODIFY COLUMN foo DATE AFTER bar");
}

public function down()
{
    DB::statement("ALTER TABLE example MODIFY COLUMN foo DATE AFTER bar"); 
}
like image 26
Odin Thunder Avatar answered Oct 11 '22 22:10

Odin Thunder