Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 342
Aleksandur Atanasov Avatar asked Feb 04 '23 22:02

Aleksandur Atanasov


2 Answers

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

like image 125
Bruce Tong Avatar answered Feb 08 '23 04:02

Bruce Tong


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.

like image 44
Rahul Avatar answered Feb 08 '23 03:02

Rahul