Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Symfony Doctrine: emojis are not stored

I am trying to save text with emojis. However emojis are not stored in text. Instead of emojis I get ? in database.

 # Doctrine Configuration
 doctrine:
     dbal:
         driver: pdo_mysql
         host: '%database_host%'
         port: '%database_port%'
         dbname: '%database_name%'
         user: '%database_user%'
         password: '%database_password%'
         charset: utf8mb4

Post class where I want to save emojis

/**
 * Post
 *
 * @ORM\Table(name="post", options={"collate"="utf8mb4_unicode_ci", "charset"="utf8mb4"})
 * @ORM\Entity(repositoryClass="AppBundle\Repository\PostRepository")
 */
class Post
    {
    /**
     * @ORM\Column(type="integer", name="id")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @ORM\Column(type="text", nullable=false, name="text")
     */
    private $text;

 }

Example

POST body

 {"text": "test 😀 test"}

text column in database

 test ? test
like image 786
misha Avatar asked Nov 19 '22 06:11

misha


1 Answers

I know it has been a while, but this solved it for me (Symfony 5):

  • On config/packages/doctrine.yaml, under dbal you must add the key-value pair charset: utf8mb4. The configuration is documented here: https://symfony.com/doc/current/reference/configuration/doctrine.html
  • If that doesn't work, you must check that in .env (or .env.local) the DATABASE_URL isn't overwriting the charset. If it is overwriting it, you just change it to utf8mb4.

This is asuming that the database is in utf8mb4. If it's not (and you can't change it) you must escape the emoji characters.

like image 126
gwelchc Avatar answered Feb 04 '23 01:02

gwelchc