Laravel Model Get Method Decoding JSON

ⅰ亾dé卋堺 提交于 2021-02-05 09:29:16

问题


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 exactly in db:

"[{\"id\":\"1\",\"country\":\"New Zealand\",\"shipping_rate\":\"1\"},{\"id\":\"2\",\"country\":\"Australia\",\"shipping_rate\":\"2\"}]"

Model Get Method:

public function getshippingAttribute()
{
    return $this->attributes['shipping'] ? json_decode(json_decode($this->attributes['shipping'])) : [];
}

回答1:


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 ...
];

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.

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.




回答2:


Try return json response

public function getshippingAttribute()
{
    return response()->json($this->attributes['shipping'])
}


来源:https://stackoverflow.com/questions/44642483/laravel-model-get-method-decoding-json

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!