Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to change mysql DB encoding charset from within a laravel migration?

I'm attempting to change the encoding of a mysql DB in Laravel-5, I've tried with a migration, following this example: https://slashdot.io/blog/adding-emoji-support-to-your-blog-948181198 - However, nothing ever updates and the charset / encoding stays as it was.

Is it possible to do this with a migration? Or will I have to write a separate script?

migration (for completeness)

/**
 * Run the migrations.
 *
 * @return void
 */
public function up()
{
    DB::raw('ALTER TABLE homestead.survey_responses CONVERT TO CHARACTER SET = utf8mb4 COLLATE = utf8mb4_unicode_ci');
    DB::raw('REPAIR TABLE homestead.survey_responses');
    DB::raw('OPTIMIZE TABLE homestead.survey_responses');
}

/**
 * Reverse the migrations.
 *
 * @return void
 */
public function down()
{
    DB::raw('ALTER TABLE homestead.survey_responses CONVERT TO CHARACTER SET = utf8 COLLATE utf8_unicode_ci');
    DB::raw('REPAIR TABLE homestead.survey_responses');
    DB::raw('OPTIMIZE TABLE homestead.survey_responses');
}

The above migration runs, without errors, but unfortunately does nothing.

like image 530
fantasitcalbeast Avatar asked Dec 03 '22 16:12

fantasitcalbeast


1 Answers

Big necro here.

Laravel 7 comes out of the box with functionality to change the charset and collation on a table. I needed this for Cashier/stripe.

The documentation shows you how to do it here

Schema::create('users', function (Blueprint $table) {
    ....
    $table->charset = 'utf8mb4';
    $table->collation = 'utf8mb4_bin';
});

Edit

Alternatively, and a better solution for me was to change the collation on a single column.

$table->string('name')->collation('utf8mb4_bin');
like image 89
Crazy World Avatar answered Dec 06 '22 09:12

Crazy World