只需覆盖asJson()
method.
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);
}
}