Advertisement
Guest User

Untitled

a guest
Jul 20th, 2019
71
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.18 KB | None | 0 0
  1. <?php
  2. use Illuminate\Support\Facades\Schema;
  3. use Illuminate\Database\Schema\Blueprint;
  4. use Illuminate\Database\Migrations\Migration;
  5. class MigrateToUtf8mb4 extends Migration
  6. {
  7. /**
  8. * Run the migrations.
  9. *
  10. * @return void
  11. */
  12. public function up()
  13. {
  14. $this->migrateCharsetTo('utf8mb4', 'utf8mb4_unicode_ci');
  15. }
  16. /**
  17. * Reverse the migrations.
  18. *
  19. * @return void
  20. */
  21. public function down()
  22. {
  23. $this->migrateCharsetTo('utf8', 'utf8_unicode_ci');
  24. }
  25. protected function migrateCharsetTo($charset, $collation)
  26. {
  27. $defaultConnection = config('database.default');
  28. $databaseName = config("database.connections.{$defaultConnection}.database");
  29. // Change default charset and collation
  30. DB::unprepared("ALTER SCHEMA {$databaseName} DEFAULT CHARACTER SET {$charset} DEFAULT COLLATE {$collation};");
  31. // Get the list of all tables
  32. $tableNames = DB::table('information_schema.tables')
  33. ->where('table_schema', $databaseName)->get(['TABLE_NAME'])->pluck('TABLE_NAME');
  34. // Iterate through the list and alter each table
  35. foreach ($tableNames as $tableName) {
  36. DB::unprepared("ALTER TABLE {$tableName} CONVERT TO CHARACTER SET {$charset} COLLATE {$collation};");
  37. }
  38. // Get the list of all columns that have a collation
  39. $columns = DB::table('information_schema.columns')
  40. ->where('table_schema', $databaseName)
  41. ->whereNotNull('COLLATION_NAME')
  42. ->get();
  43. // Iterate through the list and alter each column
  44. foreach ($columns as $column) {
  45. $tableName = $column->TABLE_NAME;
  46. $columnName = $column->COLUMN_NAME;
  47. $columnType = $column->COLUMN_TYPE;
  48. $null = 'DEFAULT NULL';
  49. if ($column->IS_NULLABLE == 'NO') {
  50. $null = 'NOT NULL';
  51. }
  52. $sql = "ALTER TABLE {$tableName}
  53. CHANGE `{$columnName}` `{$columnName}`
  54. {$columnType}
  55. CHARACTER SET {$charset}
  56. COLLATE {$collation}
  57. {$null}";
  58. DB::unprepared($sql);
  59. }
  60. }
  61. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement