Insert statements working when inserting emojis, but throws error when using eloquent
Cause of the problem:
Laravel, by default, uses utf8
as charset for MySQL. In MySQL, a UTF8 char is up to 3 bytes long (utf8
is an alias for utf8mb3
). Whereas Emoji characters are up to 4 bytes long.
Therefore we need to use utf8mb4
as our charset.
Solution:
1. Open your config/database.php
2. Find the MySQL section:
'mysql' => [ 'driver' => 'mysql', [...] 'charset' => 'utf8', 'collation' => 'utf8_unicode_ci', [....]
3. Change charset, collation to utf8mb4
and utf8mb4_unicode_ci
respectively:
'mysql' => [ 'driver' => 'mysql', [...] 'charset' => 'utf8mb4', 'collation' => 'utf8mb4_unicode_ci', [....]
4. Save and reset your database:
Note that if you reset your database, all of your data will be erased!
php artisan migrate:reset