Laravel Add a New Column to Existing Table in a Migration

Published on
2 mins read
––– views

Laravel Add a New Column to Existing Table in a Migration

Adding a new column to an existing table in Laravel involves creating a new migration. Here are the steps to achieve this:

1. Open Your Terminal

Open your terminal or command prompt.

2. Create a New Migration

Use the make:migration Artisan command to create a new migration. Replace your_migration_name with a descriptive name for your migration, and your_table_name with the name of the existing table you want to modify.

php artisan make:migration add_new_column_to_your_table --table=your_table_name

3. Open the Migration File

Navigate to the database/migrations directory and open the newly created migration file. It will be named something like 2023_12_08_add_new_column_to_your_table.php.

4. Add the New Column Definition

Inside the up method of the migration file, use the addColumn method to add the new column. Replace new_column_name with your desired column name and adjust the column type and options accordingly.

public function up()
{
    Schema::table('your_table_name', function (Blueprint $table) {
        $table->string('new_column_name')->nullable();
    });
}

5. Run the Migration

Save the migration file and run the migration using the migrate Artisan command:

php artisan migrate

This will apply the changes to your database and add the new column to the existing table.

Note

  • Adjust the column type and options (nullable, default, etc.) based on your requirements.

  • If you want to reverse the changes, you can create a rollback method in the migration file and run php artisan migrate:rollback.

By following these steps, you can easily add a new column to an existing table in Laravel using a migration.