Aleksandur Atanasov
Aleksandur Atanasov

Reputation: 141

Removing columns from migration in Laravel 5.4

I created a table using migration like:

 Schema::create('listings', function (Blueprint $table) {
        $table->increments('id');
        $table->decimal('original_price', 10, 2);
        $table->decimal('discouted_price', 10, 2);

        $table->integer('city_id')->index()->unsigned()->nullable();
        $table->foreign('city_id')->references('id')->on('cities');

        $table->integer('destination_city_id')->unsigned()->index();
        $table->foreign('destination_city_id')->references('id')->on('cities');

        $table->string('url');
        $table->string('titile');
        $table->text('description')->nullable();
        $table->dateTime('expires_at');
        $table->integer('clicks')->default('0');
        $table->integer('views')->default('0');
        $table->timestamps();
        $table->softDeletes();
    });

Now i wanna remove this two colums from ('listings').

$table->integer('city_id')->index()->unsigned()->nullable();
        $table->foreign('city_id')->references('id')->on('cities');

        $table->integer('destination_city_id')->unsigned()->index();
        $table->foreign('destination_city_id')->references('id')->on('cities');

But someone can write the this new migration how must look for remove on this two columns ?

Upvotes: 4

Views: 6443

Answers (2)

Bruce Tong
Bruce Tong

Reputation: 1431

The function for hasColumn in Laravel Schema Builder in L5.8 is as follows:

\vendor\laravel\framework\src\Illuminate\Database\Schema\Builder::hasColumn($table,$column)
{
 return in_array(
 strtolower($column), array_map('strtolower',$this->getColumnListing($table)));

so you should use your table name as the first parameter, like this

public function up() {

 if(Schema::hasColumn('listings','city_id')) {

    Schema::table('listings',function (Blueprint $table) {

      $table->dropColumn('city_id');

    });

  }

}

repeat for each column that you wish to drop

Upvotes: 4

Rahul
Rahul

Reputation: 18557

You can do like this,

if (Schema::hasColumn('city_id', 'destination_city_id'))
{      
       $table->dropForeign('city_id');
       $table->dropForeign('destination_city_id');
       $table->dropColumn(['city_id', 'destination_city_id']);
}

Its always better to check if relavant column exists in table.

Give it a try, this should work.

Upvotes: 4

Related Questions