Laravel 5模型$ cats到数组utf-8 JSON_UNESCAPED_UNICODE [英] Laravel 5 Model $cats to array utf-8 JSON_UNESCAPED_UNICODE

查看:105
本文介绍了Laravel 5模型$ cats到数组utf-8 JSON_UNESCAPED_UNICODE的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当您拥有一个数组字段并将其保存在数据库中时,它将对数组执行一个漂亮的json_encode,但没有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. The data end up like so :

<代码>{"en":"\ u039d \ u03ad \ u03b1"}

这几乎没有用.当然,解决方案是使用JSON_UNESCAPED_UNICODE标志对json_encode进行编码.是否可以告诉Laravel在保存模型之前添加此选项?

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?

我试图避免使用setNameAttribute mutator,因为每次我拥有这种类型的字段时,这样做都会很痛苦

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

推荐答案

只需覆盖 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);
    }
}

现在,您继承自 UnicodeModel 而不是 Model :

Now you inherit from UnicodeModel instead of Model:

class Cat extends UnicodeModel 
{
    // ...
}


如果您需要更好的转换控件,则可以覆盖 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 5模型$ cats到数组utf-8 JSON_UNESCAPED_UNICODE的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆