问题
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