How to move a column in a Laravel migration

This post could have also be titled “How to move a column in MySQL” or “How to move a column with SQL”… I guess you get it.

Sometimes you just have to ship it and ship it now™ and, in the heat of the moment, you could oversee the order of some database columns. Or maybe you just have OCD and need to see things organized like they should be (don’t judge me, I’m only human).

Well, worry not! While this functionality is not built in Laravel it is actually quite simple to do with a raw DB query, here you have an example in which we’re moving the external_id column after the id one:

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. In case you don’t know the syntax for a column you want to move, you could use a program like Table Plus or Sequel Pro to copy the table’s insert statement and extract the portion corresponding of the column in question.

Have you ever needed to do such a thing?

2019/07/16 EDIT:

How to set a column’s position in a Laravel migration

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Comments (

)