How to alter table in Laravel migration?

Member

by lily , in category: PHP Frameworks , 2 years ago

How to alter table in Laravel migration?

Facebook Twitter LinkedIn Telegram Whatsapp

2 answers

by herminia_bruen , 2 years 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.

Member

by rollin , a year ago

@lily 

To alter a table in Laravel migration, you can use the Schema::table method along with the desired modification methods. Here's an example of altering a table to add a new column:

  1. Open the migration file for the desired table. This file is located in the database/migrations directory.
  2. Inside the up method, use the Schema::table method to specify the table you want to alter. Pass the table name as the first argument and a closure function as the second argument.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
use IlluminateDatabaseSchemaBlueprint;
use IlluminateSupportFacadesSchema;

public function up()
{
    Schema::table('users', function (Blueprint $table) {
        // Add a new column
        $table->string('new_column')->nullable();
    });
}


In the example above, we added a new column called "new_column" of type string to the "users" table. The nullable method is used to allow null values in the new column.

  1. To apply the changes, run the migration command:
1
php artisan migrate


This will execute the migration and alter the table accordingly.


Note: If you want to revert the changes, you can create a down method in the migration file and use the appropriate Schema methods to reverse the modifications.