Home Arrow Icon Knowledge base Arrow Icon Global Arrow Icon Can I add multiple columns at once in a Laravel migration
    Laravel migrations add multiple columns Schema::table() Blueprint Laravel migration guide PHP web development


Can I add multiple columns at once in a Laravel migration


Yes, you can add multiple columns at once in a Laravel migration. Here's how:

To add multiple columns to an existing table in a Laravel migration, you can use the `Schema::table()` method and chain multiple `$table->addColumn()` calls:

php
public function up()
{
    Schema::table('users', function (Blueprint $table) {
        $table->string('address')->after('email');
        $table->string('phone')->after('address');
        $table->date('birthday')->after('phone');
    });
}

In this example, we're adding three new columns - `address`, `phone`, and `birthday` - to the `users` table. The `after()` method specifies that each new column should be added after the given column.

Alternatively, you can use the `$table->after()` method to group the new columns together:

php
public function up()
{
    Schema::table('users', function (Blueprint $table) {
        $table->after('email', function ($table) {
            $table->string('address');
            $table->string('phone');
            $table->date('birthday');
        });
    });
}

This approach produces the same result as the previous example, but it groups the new column definitions together using the `$table->after()` method.

To remove the columns later, you can use the `$table->dropColumn()` method in the `down()` method of the migration:

php
public function down()
{
    Schema::table('users', function (Blueprint $table) {
        $table->dropColumn(['address', 'phone', 'birthday']);
    });
}

Finally, run the migration to apply the changes to the database:


php artisan migrate

This will add the new `address`, `phone`, and `birthday` columns to the `users` table.

Citations:
[1] https://dev.to/vumanhtrung/add-multiple-columns-after-a-column-in-laravel-migrations-2pe6
[2] https://www.devopsschool.com/blog/how-to-add-a-column-or-columns-to-an-existing-table-using-migration-in-laravel/
[3] https://laravel-school.com/posts/how-to-add-new-columns-to-the-existing-table-in-laravel-migration-24/
[4] https://stackoverflow.com/questions/56311911/how-to-add-multiple-columns-in-already-made-table-in-laravel
[5] https://www.linkedin.com/pulse/how-add-new-column-using-laravel-migration-mahmoud-abd-elhalim