Sunday, January 16, 2022

[FIXED] JSON in longtext in mariabd returns "Could not convert database value to Doctrine type json"

Issue

Symfony 5, I write my User entity code accordingly with:
https://symfony.com/doc/current/security.html#denying-access-roles-and-other-authorization

and I use mariadb

public function getRoles(): array
    {
        $roles[] = $this->roles;
        // guarantee every user at least has ROLE_USER
        $roles[] = 'ROLE_USER';

        return array_unique($roles);
    }

and I added manually an user with role ROLE_ADMIN.

I don't understand why it returns the error:

Could not convert database value "ROLE_ADMIN" to Doctrine Type json


Solution

As I wrote, I use MariaDB. On MariaDB help, we can read : look https://mariadb.com/kb/en/json-data-type/

So I try to replace in my entity (src/Entity/User.php)

public function getRoles(): array
    {
        $roles[] = json_encode($this->roles);
        …

but it is a bad way as @yivi wrote, the first error is at value in db : be careful also if you define manually, like me, an user in database, that you enter for example ["ROLE_ADMIN"] an not ROLE_ADMIN which could returns an other error Notice: Array to string conversion because I have a second error :

$roles[] = $this->roles;
//instead of
$roles = $this->roles;

Stupid typing error



Answered By - bcag2

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.