Add Multiple Columns After a Column in Migrations

News

February 19th, 2021

laravel-migrations-after-featured.png

Laravel 8.27 introduces a new after method on the Blueprint migration instance which allows you to add multiple new columns after an existing column at the same time:

Previously, you'd have to reference each new column to get the order correct—you can see that the after cleans up this code nicely:

1Schema::table('customers', function ($table) {
2 $table->string('address_line1')->after('password');
3 $table->string('address_line2')->after('address_line1');
4 $table->string('city')->after('address_line2');
5});

While the original code isn't difficult to write, the after() method avoids repetitive after() calls for each subsequent new column and gives a nice abstraction for adding multiple columns. Pairing this with Laravel 8 migration squashing and model factory classes, Laravel continues to improve what is already some of the best migration tools available in any framework.

If you'd like to learn more about how Laravel implemented this feature, check out Pull Request #36145. Adding multiple columns after an existing column is available with the release of v8.27.0.

Filed in:

Paul Redmond

Full stack web developer. Author of Lumen Programming Guide and Docker for PHP Developers.