Check Table Exists Or Not In Laravel Migration
Let’s create a users table only if the users table doesn’t exist in the database.
<?php use Illuminate\Database\Migrations\Migration;use Illuminate\Database\Schema\Blueprint;use Illuminate\Support\Facades\Schema; class CreateUsersTable extends Migration{ /** * Run the migrations. * * @return void */ public function up() { /* * If users table does not exists then create * Your newly appended changes won't be added if table already exists */ if (!Schema::hasTable('users')) { Schema::create('users', function (Blueprint $table) { $table->id(); $table->uuid('uuid')->unique(); $table->text('title')->nullable(); $table->text('first_name'); $table->text('middle_name')->nullable(); $table->text('last_name'); $table->string('email')->unique(); $table->string('password')->nullable(); $table->text('gender')->nullable(); $table->timestamps(); }); } } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('users'); }} Check Column Exists or Not In Laravel Migration
Let’s suppose, after migrating the database we want remove the 2 columns `middle_name` and `gender`.<?php use Illuminate\Database\Migrations\Migration;use Illuminate\Database\Schema\Blueprint;use Illuminate\Support\Facades\Schema; class UpdateUsersTable extends Migration{ /** * Run the migrations. * * @return void */ public function up() { Schema::table('users', function (Blueprint $table) { // The "users" table exists and has an "middle_name" column... if (Schema::hasColumn('users', 'middle_name')) { $table->dropColumn('middle_name'); } if (Schema::hasColumn('users', 'gender')) { $table->dropColumn('gender'); } }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::table('users', function (Blueprint $table) { if (!Schema::hasColumn('users', 'middle_name')) { $table->text('middle_name')->nullable()->after('first_name'); } if (!Schema::hasColumn('users', 'gender')) { $table->text('gender')->nullable()->after('password'); } }); }}
Comments
Post a Comment