laravel 🚀
json 🚀
note2self 🚀
Laravel and Casting JSON_UNESCAPED_UNICODE Data

Had a interesting issue with Laravel and the cast feature

Basically a Chinese set of characters would be converted to their unicode counterpart http://php.net/manual/en/json.constants.php

So saving "你好,世界" would become "\u4f60\u597d\uff0c\u4e16\u754c" in the database.

Making it hard to search for "你好,世界"

But I just wanted this data as it was, so later I could query the data and interact with it in it's default character state.

Digging into the Model class vendor/laravel/framework/src/Illuminate/Database/Eloquent/Model.php:3044 I found that this method would json_encode but with no options.

So on my model I had to override that

    protected function asJson($value)
    {
        /**
         * Alter Cast
         * Default is altering unicode
         */
        return json_encode($value, JSON_UNESCAPED_UNICODE);
    }

And now "你好,世界" would save that way to the database and not "\u4f60\u597d\uff0c\u4e16\u754c"