ONYX
ONYX

Reputation: 5859

Laravel Model Get Method Decoding JSON

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'])) : [];
}

Upvotes: 1

Views: 2336

Answers (3)

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

Upvotes: 0

The Alpha
The Alpha

Reputation: 146191

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.

Upvotes: 3

MrCharif
MrCharif

Reputation: 49

Try return json response

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

Upvotes: -1

Related Questions