How to alter table in Laravel migration?

Member

by lily , in category: PHP Frameworks , 9 months ago

How to alter table in Laravel migration?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by herminia_bruen , 3 months ago

@lily 

To alter a table using migrations in Laravel, you can use the Schema facade's table method and pass it the name of the table you want to alter. You can then chain various column manipulation methods to the table method to make the desired changes.


Here is an example of how you can use the table method to add a new column to a table:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
use IlluminateSupportFacadesSchema;
use IlluminateDatabaseSchemaBlueprint;
use IlluminateDatabaseMigrationsMigration;

class AddNewColumnToUsersTable extends Migration
{
    public function up()
    {
        Schema::table('users', function (Blueprint $table) {
            $table->string('new_column')->nullable();
        });
    }

    public function down()
    {
        Schema::table('users', function (Blueprint $table) {
            $table->dropColumn('new_column');
        });
    }
}


The up method is used to make the desired changes to the table, while the down method should revert those changes.


You can also use other column manipulation methods such as renameColumn, change, and dropColumn to alter the table as needed.


Once you have written your migration class, you can run it using the php artisan migrate command.