简体   繁体   English

Laravel 5 Model $ cats to array utf-8 JSON_UNESCAPED_UNICODE

[英]Laravel 5 Model $cats to array utf-8 JSON_UNESCAPED_UNICODE

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. 当你有一个数组字段并将其保存在数据库中时,它会为数组提供一个漂亮的json_encode但没有JSON_UNESCAPED_UNICODE选项。 The data end up like so : 数据最终如下:

{"en":"\Ν\έ\α"}

which is pretty much useless. 这几乎没用。 The solution of course is to json_encode with the JSON_UNESCAPED_UNICODE flag. 解决方案当然是json_encode和JSON_UNESCAPED_UNICODE标志。 Is it possible to tell Laravel to add this option before saving the model? 在保存模型之前,是否可以告诉Laravel添加此选项?

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 我试图避免使用setNameAttribute mutator,因为每次我有这种类型的字段时这样做会很麻烦

Just override the asJson() method. 只需覆盖asJson()方法即可。

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 : 现在您继承自UnicodeModel而不是Model

class Cat extends UnicodeModel 
{
    // ...
}

In case you need a finer casting control you can override the setAttribute method, eg: 如果您需要更精细的转换控件,您可以覆盖setAttribute方法,例如:

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);
    }
}

更适合Laravel的模型

$yourModel->toJson(JSON_UNESCAPED_UNICODE)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM