Search code examples
phpmysqleloquentlaravel-5

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.


Solution

  • It's not possible using Schema/Blueprint classes that are usually used in migration classes. But you can still run any SQL you need using DB facade - in your case:

    use Illuminate\Database\Migrations\Migration;
    use Illuminate\Support\Facades\DB;
    
    class ChangeCharsetAndCollation Migration
    {
        public function up()
        {
            DB::statement('ALTER DATABASE database CHARACTER SET new_charset COLLATE new_collation');
        }
    
        public function down()
        {
            DB::statement('ALTER DATABASE database CHARACTER SET old_charset COLLATE old_collation');
        }
    }
    

    Just replace database, old_charset, old_collation, new_charset, new_collation with desired values and make sure your user has permissions to run such query.