Check If a Column Exists in Laravel Migration File

问题: Already I have a table name table_one. Now I want to add two more columns to it. Everything works fine so far. But in my method, I want to check a column exists or not in m...

问题:

Already I have a table name table_one. Now I want to add two more columns to it. Everything works fine so far. But in my method, I want to check a column exists or not in my table like dropIfExists('table').

/**
 * Run the migrations.
 *
 * @return void
 */
public function up()
{
    Schema::table('table_one', function (Blueprint $table) {
        $table->string('column_one')->nullable();
        $table->string('column_two')->nullable();
    });
}

/**
 * Reverse the migrations.
 *
 * @return void
 */
public function down()
{
    Schema::table('table_one', function (Blueprint $table) {
        // in here i want to check column_one and column_two exists or not
        $table->dropColumn('column_one');
        $table->dropColumn('column_two');
    });
}

回答1:

You need something just like this

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

回答2:

Just break the schema up into two calls

public function up()
{
    Schema::table('table_one', function (Blueprint $table) {
        $table->dropColumn(['column_one', 'column_two']);
    });

    Schema::table('table_one', function (Blueprint $table) {
        $table->string('column_one')->nullable();
        $table->string('column_two')->nullable();
    });
}
  • 发表于 2019-01-18 04:00
  • 阅读 ( 190 )
  • 分类:网络文章

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除