当你有一个数组字段并将其保存在数据库中时,它会为数组提供一个漂亮的json_encode但没有JSON_UNESCAPED_UNICODE选项。数据最终如下:
{"en":"\u039d\u03ad\u03b1"}
这几乎没用。解决方案当然是json_encode和JSON_UNESCAPED_UNICODE标志。 在保存模型之前,是否可以告诉Laravel添加此选项?
我试图避免使用setNameAttribute mutator,因为每次我有这种类型的字段时都会这样做很麻烦
答案 0 :(得分:7)
只需覆盖asJson()
方法。
class Cat extends Model
{
// ...
protected function asJson($value)
{
return json_encode($value, JSON_UNESCAPED_UNICODE);
}
}
如果您不想为所有模型重复此方法,只需将方法提取到抽象类:
abstract class UnicodeModel extends Model
{
protected function asJson($value)
{
return json_encode($value, JSON_UNESCAPED_UNICODE);
}
}
现在您从UnicodeModel
而不是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);
}
}
答案 1 :(得分:1)
更好的 Laravel模型:
$yourModel->toJson(JSON_UNESCAPED_UNICODE)