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

In a past post I wrote about How to move a column in a Laravel migration, but sometimes you’re better prepared and want to define the position of the column while creating it.

Fortunately Laravel makes this real simple and we can fluently decide if a column must be positioned first or after another.

To put the column in the first place we use ->first(), for example:

// Place the column first
Schema::table('users', function (Blueprint $table) {
    $table->string('external_id')->first();
});

To put the column after another we use ->after('column'), for example:

// Place the column after another column 
Schema::table('users', function (Blueprint $table) {
    $table->string('external_id')->after('id');
});

And that’s all, I hope someone finds it useful.

Leave a comment

Your email address will not be published.

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