Laravel 5 Model $cats to array utf-8 JSON_UNESCAPED_UNICODE

廉价感情. 提交于 2020-08-03 03:21:07

问题


When you have an array field and save it in the DB it does a nifty json_encode to the array but without the JSON_UNESCAPED_UNICODE option. The data end up like so :

{"en":"\u039d\u03ad\u03b1"}

which is pretty much useless. The solution of course is to json_encode with the JSON_UNESCAPED_UNICODE flag. Is it possible to tell Laravel to add this option before saving the model?

I am trying to avoid using the setNameAttribute mutator as this would be kind of a pain to do it every time i have this type of fields


回答1:


Just override the asJson() method.

class Cat extends Model
{

    // ...

    protected function asJson($value)
    {
        return json_encode($value, JSON_UNESCAPED_UNICODE);
    }

}

If you don't want to repeat the method for all your models, just extract the method to an abstract class:

abstract class UnicodeModel extends Model 
{
    protected function asJson($value)
    {
        return json_encode($value, JSON_UNESCAPED_UNICODE);
    }
}

Now you inherit from UnicodeModel instead of Model:

class Cat extends UnicodeModel 
{
    // ...
}

In case you need a finer casting control you can override the setAttribute method, e.g.:

class Cat extends Model
{

    // ...

    public function setAttribute($key, $value)
    {

        // take special care for the attributes foo, bar and baz
        if (in_array($key, ['foo', 'bar', 'baz'])) {
            $this->attributes[$key] = json_encode($value, JSON_UNESCAPED_UNICODE);

            return $this;
        }

        // apply default for everything else
        return parent::setAttribute($key, $value);
    }
}



回答2:


Better for Laravel's Model:

$yourModel->toJson(JSON_UNESCAPED_UNICODE)


来源:https://stackoverflow.com/questions/38241424/laravel-5-model-cats-to-array-utf-8-json-unescaped-unicode

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!