[英]Laravel 5 Model $cats to array utf-8 JSON_UNESCAPED_UNICODE
當你有一個數組字段並將其保存在數據庫中時,它會為數組提供一個漂亮的json_encode但沒有JSON_UNESCAPED_UNICODE選項。 數據最終如下:
{"en":"\Ν\έ\α"}
這幾乎沒用。 解決方案當然是json_encode和JSON_UNESCAPED_UNICODE標志。 在保存模型之前,是否可以告訴Laravel添加此選項?
我試圖避免使用setNameAttribute mutator,因為每次我有這種類型的字段時這樣做會很麻煩
只需覆蓋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);
}
}
更適合Laravel的模型 :
$yourModel->toJson(JSON_UNESCAPED_UNICODE)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.