Add a new column to existing table in a migration

前端 未结 12 2656
离开以前
离开以前 2020-11-28 17:09

I can\'t figure out how to add a new column to my existing database table using the Laravel framework.

I tried to edit the migration file using...



        
12条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-11-28 18:04

    To create a migration, you may use the migrate:make command on the Artisan CLI. Use a specific name to avoid clashing with existing models

    for Laravel 3:

    php artisan migrate:make add_paid_to_users
    

    for Laravel 5+:

    php artisan make:migration add_paid_to_users_table --table=users
    

    You then need to use the Schema::table() method (as you're accessing an existing table, not creating a new one). And you can add a column like this:

    public function up()
    {
        Schema::table('users', function($table) {
            $table->integer('paid');
        });
    }
    

    and don't forget to add the rollback option:

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

    Then you can run your migrations:

    php artisan migrate
    

    This is all well covered in the documentation for both Laravel 3:

    • Schema Builder
    • Migrations

    And for Laravel 4 / Laravel 5:

    • Schema Builder
    • Migrations

    Edit:

    use $table->integer('paid')->after('whichever_column'); to add this field after specific column.

提交回复
热议问题