Laravel migration add new column

To add a new column to a table in Laravel using migrations, you can follow these steps:

  1. Open the terminal and navigate to the root directory of your Laravel project.

  2. Run the following command to create a new migration:

    php artisan make:migration add_new_column_to_table

    This will create a new migration file in the database/migrations directory.

  3. Open the newly created migration file and add the following code:

    
    use Illuminate\Database\Migrations\Migration;
    use Illuminate\Database\Schema\Blueprint;

class AddNewColumnToTable extends Migration { /**

/**
 * Reverse the migrations.
 *
 * @return void
 */
public function down()
{
    Schema::table('table_name', function (Blueprint $table) {
        $table->dropColumn('new_column_name');
    });
}

}

Replace `table_name` with the actual name of the table you want to add the new column to, and `new_column_name` with the actual name of the new column.

4. Run the following command to execute the migration:

php artisan migrate

This will add the new column to the specified table.

5. If you want to add a default value to the new column, you can do so by adding the `default` method to the `up` method:

$table->string('new_column_name')->default('default_value');

Replace `default_value` with the actual default value you want to set for the new column.

6. If you want to add a nullable column, you can do so by adding the `nullable` method to the `up` method:

$table->string('new_column_name')->nullable();

This will make the new column nullable, meaning it can be left blank.

7. If you want to add a unique column, you can do so by adding the `unique` method to the `up` method:

$table->string('new_column_name')->unique();

This will make the new column unique, meaning it cannot have duplicate values.

8. If you want to add a foreign key column, you can do so by adding the `foreign` method to the `up` method:

$table->integer('foreign_key_column')->unsigned()->nullable(); $table->foreign('foreign_key_column')->references('id')->on('other_table');

Replace `other_table` with the actual name of the table that the foreign key references.

9. Once you've added the new column, you can run the following command to roll back the migration:

php artisan migrate:rollback

This will remove the new column from the table.

10. If you want to add a new column to a table that already exists, you can use the `Schema::table` method to add the new column:

Schema::table('table_name', function (Blueprint $table) { $table->string('new_column_name'); });


This will add the new column to the specified table without creating a new migration.