Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing the Collation of database column is not working in laravel migrations

I want to change the collation of the column "about_me" from "users" table. For that, I am using below code. I am simply changing the collation to utf8mb4_unicode_ci but the code is not working.

 public function up()
    {
        if (Schema::hasColumn("users", "about_me")) {
            Schema::table("users", function(Blueprint $table) {
                $table->collation = 'utf8mb4_unicode_ci';
                $table->charset = 'utf8mb4';
            });
        }
 }

I already changed in /config/database.php, this helped me to save the data in db but after fetching the database, I found the special symbols are not displaying, when I changed the Collation of that column to utf8mb4_unicode_ci then it worked fine. But I want to make it in migration. The current code is not working, I need the correct code which works well.

like image 659
KRY Avatar asked Dec 07 '22 16:12

KRY


2 Answers

Laravel supports modifying collation per column basis for MySQL. For a table wide modification, you need to write a raw query.

public function up()
{

    DB::statement("ALTER TABLE users CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci");
}
like image 115
Oluwafemi Sule Avatar answered Dec 10 '22 23:12

Oluwafemi Sule


In modern Laravel there are charset and collations that can be set on table or columns.

https://laravel.com/docs/8.x/migrations#database-connection-table-options

    // You can change table.
    Schema::table('users`', function (Blueprint $table) {
        $table->charset = 'utf8mb4';
        $table->collation = 'utf8mb4_unicode_ci';
    });

    // You can change on a field of a table.
    Schema::table('users', function (Blueprint $table) {
        $table->string('about_me')->charset('utf8mb4')->collation('utf8mb4_unicode_ci')->change();
    });
like image 32
Liam Mitchell Avatar answered Dec 10 '22 22:12

Liam Mitchell