rocket_moon
rocket_moon

Reputation: 309

Laravel/Vue - Passing data : Json Nested values as string

I'm tring to pass a JSON object from my Laravel backend to my Vue frontend, but one of the nested properties is being returned as string instead of an object. The object in question is user.options as seen below.

The user.options object is well formated, but when I send the response it is being treated as string. I can convert the string to JSON in the frontend but it is not ideal.

JSON code snippet of user object with malformed options property

public function update(Request $request)
{
    $user = $this->user;
    $user->options = json_encode([
        'cart' => $request->only('product_id', 'code', 'product_slug', 'pic_url', 'request')
    ]);
    $user->save();

    return response()->json($user);
}

Upvotes: 1

Views: 650

Answers (1)

Namoshek
Namoshek

Reputation: 6544

It is not necessary to serialize JSON of a property manually. Instead, you can make use of Eloquent's $casts property to define that your options should be treated as object:

class User
{
    /**
     * The attributes that should be cast to native types.
     *
     * @var array
     */
    protected $casts = [
        'options' => 'object',
    ];
}

You can then assign arrays and objects to this property. Eloquent will store it as JSON in the background. When you retrieve the property, Eloquent will transform it back to an object again:

public function update(Request $request) {
    $user = $this->user;
    $user->options = [
        'cart' =>  $request->only('product_id', 'code', 'product_slug', 'pic_url', 'request')
    ];
    $user->save();

    return response()->json($user);
}

Upvotes: 1

Related Questions