HDTuto.com

Laravel - Drop column if exists using migration


it is a very small point for database. as know well for laravel then we always use migration for creating table or add new column in table, also if you need to remove column. but it is good way if you check column if exists or not before drop column in migration. so you can it using schema method.

You can see we can use hasColumn(), as you can see below:

Schema::hasColumn(table_name, column_name);

Now you can see below full migration code with example:

<?php


use Illuminate\Support\Facades\Schema;

use Illuminate\Database\Schema\Blueprint;

use Illuminate\Database\Migrations\Migration;


class CreateUsersTable extends Migration

{

public function up()

{

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

$table->increments('id');

$table->string('name');

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

$table->string('password');

$table->rememberToken();

$table->timestamps();

});

}

public function down()

{

if (Schema::hasColumn('users', 'name'))

{

Schema::table('users', function (Blueprint $table)

{

$table->dropColumn('name');

});

}

}

}

I hope it can help you....




June 24, 2018 | Category : PHP Laravel Laravel 5 Laravel 5.5 Laravel 5.6
Related Posts