简体   繁体   中英

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. 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. 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

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, eg:

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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