select(DB::raw('MAX(id) as id')) ->groupBy('company_id') ->pluck('id') ->toArray(); if (!empty($latestPerCompany)) { // Set user_id to NULL on the kept records (making them company-wide) DB::table('lead_user_field_settings') ->whereIn('id', $latestPerCompany) ->update(['user_id' => null]); // Delete all other (per-user) records DB::table('lead_user_field_settings') ->whereNotIn('id', $latestPerCompany) ->delete(); } // Drop old unique constraint and add new one Schema::table('lead_user_field_settings', function (Blueprint $table) { $table->dropUnique('lead_user_field_settings_company_user_unique'); }); Schema::table('lead_user_field_settings', function (Blueprint $table) { $table->unsignedInteger('user_id')->nullable()->change(); $table->unique(['company_id'], 'lead_field_settings_company_unique'); }); } public function down() { Schema::table('lead_user_field_settings', function (Blueprint $table) { $table->dropUnique('lead_field_settings_company_unique'); }); Schema::table('lead_user_field_settings', function (Blueprint $table) { $table->unsignedInteger('user_id')->nullable(false)->change(); $table->unique(['company_id', 'user_id'], 'lead_user_field_settings_company_user_unique'); }); } }