Laravel模型获取方法解码JSON [英] Laravel Model Get Method Decoding JSON
问题描述
您好,下面是我存储在数据库中的内容,但是当我在模型中使用get方法时,在格式化数据时必须两次使用json_decode,为什么会发生这种情况,我能否以某种方式使用它一次?
Hi there below is what I'm storing in my db but when I use my get method in my model I have to use json_decode twice when formating my data why is this happening and can I have it just use it once somehow.
json:
"[{\"id\":\"1\",\"country\":\"New Zealand\",\"shipping_rate\":\"1\"},{\"id\":\"2\",\"country\":\"Australia\",\"shipping_rate\":\"2\"}]"
模型获取方法:
public function getshippingAttribute()
{
return $this->attributes['shipping'] ? json_decode(json_decode($this->attributes['shipping'])) : [];
}
推荐答案
问题从您的问题来看还不够清楚,但是 v-5.1 ).在这种情况下,只需在模型中声明一个 $ casts
属性即可,例如:
The problem is not clear enough from your question but the Laravel offers a builtin mechanism for attribute casting (Since v-5.1). In this case, in your model, just declare a $casts
property for example:
protected $casts = [
'shipping' => 'array',
// more ...
];
由于上面给出的 $ casts
属性,每当编写(创建/更新)模型时,您无需显式使用 json_encode
进行转换数组为 json
字符串, Laravel
将为您完成此操作,并且,当您检索模型(单个/集合)时,发货
属性将自动转换回 array
,因此您无需使用 json_decode
即可处理该属性.
Because of the $casts
property given above, whenever you'll write (create/update) a model, you don't need to explicitly use json_encode
to convert the array to json
string, Laravel
will do it for you and also, when you'll retrieve the model (single/collection), the shipping
attribute will be automatically converted back to an array
so you don't need to use json_decode
for working with the attribute.
关于响应,如果您不手动将其转换为 json
(返回 model/collection
时),laravel也将处理该响应.这可能会解决您的问题.
Regarding the response, that will be also handled by laravel if you don't convert it to json
manually (when returning a model/collection
). This will possibly solve your problem.
这篇关于Laravel模型获取方法解码JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!