Make sure the mysql version you are using supports utf8mb4.
SQLSTATE[HY000]: General error: 1366 Incorrect string value
Hello guys,
I'm almost pulling my hair over here after trying to solve this problem for hours. The thing is, whenever I try to run my database seeder, I keep getting this error telling me I have a incorrect string value.
[Illuminate\Database\QueryException]
SQLSTATE[HY000]: General error: 1366 Incorrect string value: '\xE3\xB3nica'
for column 'nome' at row 1 (SQL: insert into `utilizadores` (`nome`, `apel
ido`, `email`, `password`, `verificado`, `token_verificacao`, `id_unidade`,
`atualizado_em`, `criado_em`) values (ver�nica, pinto, [email protected]
t, $2y$10$24vkB6XXGBsEQgsVQo8MOuw9PGHlu1lEMGoan8PP/8imeW80hWmMW, 1, , 1, 20
17-07-21 01:40:49, 2017-07-21 01:40:49))
[Doctrine\DBAL\Driver\PDOException]
SQLSTATE[HY000]: General error: 1366 Incorrect string value: '\xE3\xB3nica'
for column 'nome' at row 1
[PDOException]
SQLSTATE[HY000]: General error: 1366 Incorrect string value: '\xE3\xB3nica'
for column 'nome' at row 1
And this is the factory for the model:
$factory->define(Utilizador::class, function (Faker\Generator $faker) {
$faker = Faker\Factory::create('pt_PT');
static $password;
$unidades = Unidade::all()->pluck('id')->toArray();
return [
'nome' => $faker->firstName,
'apelido' => $faker->lastName,
'email' => $faker->unique()->safeEmail,
'password' => $password ?: $password = bcrypt('123456'),
'verificado' => $verificado = $faker->randomElement([Utilizador::UTILIZADOR_VERIFICADO, Utilizador::UTILIZADOR_NAO_VERIFICADO]),
'token_verificacao' => $verificado == Utilizador::UTILIZADOR_VERIFICADO ? null : Utilizador::generateVerificationCode(),
'id_unidade' => $faker->randomElement($unidades),
];
});
As you can see, it looks like it is related to encoding. But I've set my charset to utf8mb4 and my collation to utf8mb4_unicode_ci.
Back in Laravel 5.3 I didn't face this kind of problem while using utf8 and utf8_unicode_ci.
Hey guys, I finally found out why my code was behaving like that. The thing is, I was using strtolower in a part of my code when that specific model was being updated:
public function setNomeAttribute($nome)
{
$this->attributes['nome'] = strtolower($nome);
}
I got it working after changing it to mb_strtolower, that is the one that should be used when working with international strings.
public function setNomeAttribute($nome)
{
$this->attributes['nome'] = mb_strtolower($nome);
}
This was the github answer that helped me:
visit https://stackoverflow.com/questions/26343876/laravel-utf-8-to-database
I hope it helps others that may be facing the same problem.
Please or to participate in this conversation.